SDL渲染RGB数据到Qt中的控件

用到的知识

 
SDL渲染RGB数据到Qt中的控件通过定时器刷新

SdlQtRGB.h

#pragma once

#include <QtWidgets/QWidget>
#include "ui_SdlQtRGB.h"

class SdlQtRGB : public QWidget
{
    Q_OBJECT

public:
    SdlQtRGB(QWidget *parent = Q_NULLPTR);
    ~SdlQtRGB();

private:
    Ui::SdlQtRGBClass ui;

    void timerEvent(QTimerEvent* evt) override;
};

SdlQtRGB.cpp

#include "SdlQtRGB.h"
#include "sdl/SDL.h"
#include <iostream>

#pragma comment(lib, "SDL2.lib")
using namespace std;

static SDL_Window* sdl_win = nullptr;
static SDL_Renderer* sdl_render = nullptr;
static SDL_Texture* sdl_texture = nullptr;
static unsigned char* rgb = nullptr;
static int sdl_width = 0;
static int sdl_height = 0;
static int pixel_size = 4;

void SdlQtRGB::timerEvent(QTimerEvent* evt)
{
    SDL_Rect rect;
    static unsigned char tmp = 255;

    rect.x = 0;
    rect.y = 0;
    rect.w = sdl_width;
    rect.h = sdl_height;

    for (int i = 0; i < sdl_height; i++)
    {
        int b = i * sdl_width * pixel_size;

        for (int j = 0; j < sdl_width * pixel_size; j += pixel_size)
        {
            rgb[b + j] = 0;        // B
            rgb[b + j + 1] = tmp;  // G
            rgb[b + j + 2] = 0;    // R
            rgb[b + j + 3] = 0;    // A
        }
    }

    tmp--;

    SDL_RenderClear(sdl_render);
    SDL_UpdateTexture(sdl_texture, nullptr, rgb, sdl_width * pixel_size);
    SDL_RenderCopy(sdl_render, sdl_texture, nullptr, &rect);
    SDL_RenderPresent(sdl_render);
}

SdlQtRGB::SdlQtRGB(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
 
    sdl_width = ui.label->width();
    sdl_height = ui.label->height();

    // 初始化 SDL
    if (SDL_Init(SDL_INIT_VIDEO))
    {
        cout << SDL_GetError() << endl;
    }

    // 创建窗口
    sdl_win = SDL_CreateWindowFrom((void*)ui.label->winId());  // 通过 Qt 控件中的句柄来创建窗口

    if (!sdl_win)
    {
        cout << SDL_GetError() << endl;
    }

    // 创建渲染器
    sdl_render = SDL_CreateRenderer(sdl_win, -1, SDL_RENDERER_ACCELERATED);

    if (!sdl_render)
    {
        cout << SDL_GetError() << endl;
    }

    // 创建材质
    sdl_texture = SDL_CreateTexture(sdl_render, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, sdl_width, sdl_height);

    if (!sdl_texture)
    {
        cout << SDL_GetError() << endl;
    }

    rgb = new unsigned char[sdl_width * sdl_height * pixel_size];

    startTimer(10);  // 每过10ms就会调用一次 timerEvent,1s大约有100帧的图像
}

SdlQtRGB::~SdlQtRGB()
{
    delete[] rgb;
}

每过10ms就进行一次图像的渲染。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值