实例
代码
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>
#include <QImage>
#include <QMessageBox>
#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 + 1] = tmp; // G
}
}
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)
{
QImage img1("001.png");
QImage img2("002.png");
if (img1.isNull() || img2.isNull())
{
QMessageBox::information(this, "information", "open image failed!");
}
ui.setupUi(this);
/* 对两幅图像进行横向拼接,宽为两幅图片的宽相加,高为两幅图片的较大高 */
sdl_width = img1.width() + img2.width();
sdl_height = (img1.height() > img2.height() ? img1.height() : img2.height());
resize(sdl_width, sdl_height);
ui.label->move(0, 0);
ui.label->resize(sdl_width, sdl_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];
// 每个像素点重置为透明
memset(rgb, sizeof(rgb), 0);
/* 对需要拼接的两幅图片进行一行一行的拷贝 */
for (int i = 0; i < sdl_height; i++)
{
int b = i * sdl_width * pixel_size;
/* 拷贝 img1 的第i行 */
if (i < img1.height())
{
memcpy(rgb + b, img1.scanLine(i), img1.width() * pixel_size);
}
b += img1.width() * pixel_size;
/* 拷贝 img2 的第i行 */
if (i < img2.height())
{
memcpy(rgb + b, img2.scanLine(i), img2.width() * pixel_size);
}
}
QImage out(rgb, sdl_width, sdl_height, QImage::Format_ARGB32);
out.save("out.png"); // 将拼接后的图像保存为 out.png
startTimer(10); // 每过10ms就会调用一次 timerEvent,1s大约有100帧的图像
}
SdlQtRGB::~SdlQtRGB()
{
delete[] rgb;
}
拼接后的图像效果