SDL渲染合并两张图片

65 阅读1分钟
#include "sdlqtrgb.h"
#include <SDL2/SDL.h>
#include <QImage>
#include <QMessage>

// 添加库

#pragma comment(lib, "SDL2.lib")

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


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

    // 初始化

    SDL_Init(SDL_INIT_VIDEO);

    // 创建窗口,
    // 传的参数为窗口句柄

    sdl_win = SDL_CreateWindowFrom((void *)ui.label->winId());

    // 创建渲染器
    // SDL_RENDERER_ACCELERATED参数表示硬件加速

    sdl_render = SDL_CreateRenderer(sdl_win, -1, SDL_RENDERER_ACCELERATED);

    QImage img1("001.png");
    QImage img2("002.png");

    if (img1.isNull() || img2.isNull()) {
        QmessageBox::information(this,"", "open image failed!");
        return;
    }

    // 图像宽度

    int out_w = img1.width() + img2.width();

    // 图像高度,图片为左右拼接

    int out_h = img1.height();

    if (out_h < img2.height()) out_h = img2.height();

    sdl_width = out_w;
    sdl_height = out_h;
    resize(sdl_width, sdl_height);



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

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

    // 默认设置为透明
    memset(rgb, 0, sdl_width * sdl_height * 4);

    // 合并两幅图像
    for (int i = 0; i < sdl_height; i++)
    {
        int b = i * sdl_width * 4;

        if ( i < img1.height()) {
            memcpy(rgb +b, img1.scanLine(i), img1.width() * 4);
        }

        // 拷贝第二幅图片
        b += img2.width() * 4;
         if ( i < img1.height()) {
            memcpy(rgb +b, img2.scanLine(i), img2.width() * 4);
        }


    }
    
    // 保存图片
    QImage(rgb, sdl_width, sdl_height, QImage::Format_ARGB32);
    out.save("out.png");

    // 启动定时器,间隔10毫秒
    startTimer(10);
}

SDLQtRGB::~SDLQtRGB()
{}

void SDLQtRGB::timerEvent(QTimerEvent* event)
{
    {
        int b = j * sdl_width * 4;
        for (int i = 0; i < sdl_width * 4; i += 4)
        {
            rgb[b + i] = tmp;  //  R
            rgb[b + i + 1] = 0; // G
            rgb[b + i + 2] = 0;  // B
            rgb[b + i + 3] = 0; // A
        }
    }

    // 更新材质

    SDL_UpdateTexture(sdl_texture, NULL, rgb, sdl_width * 4);

    // 清理画面

    SDL_RenderClear(sdl_render);

    // 把材质拷贝到渲染器中

    SDL_Rect rect;  // 定义目标位置
    rect.x = 0;
    rect.y = 0;
    rect.w = sdl_width;
    rect.h = sdl_height;

    SDL_RenderCopy(sdl_render, sdl_texture, NULL, &rect);

    // 渲染

    SDL_RenderPresent(sdl_render);

}