前言
SDL中内置加载BMP的API,使用起来会更加简单,便于初学者学习使用SDL
如果需要加载JPG、PNG等其他格式的图片,可以使用第三方库:SDL_image
测试环境:
- ffmpeg的4.3.2自行编译版本
- windows环境
- qt5.12
- sdl2.0.22(mingw编译器)
完整代码:
SdlShowBmpThread.h
#ifndef SDLSHOWBMPTHREAD_H
#define SDLSHOWBMPTHREAD_H#include <QObject>
#include <QThread>class SdlShowBmpThread : public QThread
{Q_OBJECT
public:explicit SdlShowBmpThread(QObject *parent = nullptr);~SdlShowBmpThread();signals:// QThread interface
protected:virtual void run() override;
};#endif // SDLSHOWBMPTHREAD_H
SdlShowBmpThread.cpp
#include "sdlshowbmpthread.h"#include <QDebug>
#include <SDL2/SDL.h>#define END(judge, func) \if (judge) { \qDebug() << #func << "error" << SDL_GetError(); \goto end; \}SdlShowBmpThread::SdlShowBmpThread(QObject *parent) : QThread(parent)
{// 当监听到线程结束时(finished),就调用deleteLater回收内存connect(this,&SdlShowBmpThread::finished,this,[=](){this->deleteLater();qDebug()<<"SdlPlayWavThread线程结束";});
}SdlShowBmpThread::~SdlShowBmpThread()
{// 断开所有的连接disconnect();// 内存回收之前,正常结束线程requestInterruption();// 安全退出quit();wait();qDebug() << this << "析构(内存被回收)";
}void SdlShowBmpThread::run()
{// 像素数据SDL_Surface *surface = nullptr;// 窗口SDL_Window *window = nullptr;// 渲染上下文SDL_Renderer *renderer = nullptr;// 纹理(直接跟特定驱动程序相关的像素数据)SDL_Texture *texture = nullptr;// 矩形框SDL_Rect srcRect = {0, 0, 1928, 1048}; //源图片从0,0坐标截取1928*1048尺寸大小的图片SDL_Rect dstRect = {0, 0, 1928, 1048}; //目标图片在0,0左边显示1928*1048大小的图片SDL_Rect rect;// 初始化子系统END(SDL_Init(SDL_INIT_VIDEO), SDL_Init);// 加载BMPsurface = SDL_LoadBMP("E:/media/picture-test.bmp");END(!surface, SDL_LoadBMP);// 创建窗口window = SDL_CreateWindow(// 标题"SDL显示BMP图片",// xSDL_WINDOWPOS_UNDEFINED,// ySDL_WINDOWPOS_UNDEFINED,// wsurface->w,// hsurface->h,SDL_WINDOW_SHOWN);END(!window, SDL_CreateWindow);// 创建渲染上下文renderer = SDL_CreateRenderer(window, -1,SDL_RENDERER_ACCELERATED |SDL_RENDERER_PRESENTVSYNC);if (!renderer) {renderer = SDL_CreateRenderer(window, -1, 0);END(!renderer, SDL_CreateRenderer);}// 创建纹理texture = SDL_CreateTextureFromSurface(renderer, surface);END(!texture, SDL_CreateTextureFromSurface);// 画一个红色的矩形框END(SDL_SetRenderDrawColor(renderer,255, 0, 0, SDL_ALPHA_OPAQUE),SDL_SetRenderDrawColor);rect = {0, 0, 50, 50};END(SDL_RenderFillRect(renderer, &rect),SDL_RenderFillRect);// 设置绘制颜色(画笔颜色)END(SDL_SetRenderDrawColor(renderer,255, 255, 0, SDL_ALPHA_OPAQUE),SDL_SetRenderDrawColor);// 用绘制颜色(画笔颜色)清除渲染目标END(SDL_RenderClear(renderer),SDL_RenderClear);// 拷贝纹理数据到渲染目标(默认是window)END(SDL_RenderCopy(renderer, texture, &srcRect, &dstRect),SDL_RenderCopy);// 更新所有的渲染操作到屏幕上SDL_RenderPresent(renderer);SDL_Delay(2000);end:SDL_FreeSurface(surface);SDL_DestroyTexture(texture);SDL_DestroyRenderer(renderer);SDL_DestroyWindow(window);SDL_Quit();
}
线程调用:
void MainWindow::on_pushButton_sdl_show_bmp_clicked()
{m_pSdlShowBmpThread=new SdlShowBmpThread(this);m_pSdlShowBmpThread->start();
}
注意:.h文件中提前声明了以下全局变量
SdlShowBmpThread *m_pSdlShowBmpThread=nullptr;
注意:本文为个人记录,新手照搬可能会出现各种问题,请谨慎使用
码字不易,如果这篇博客对你有帮助,麻烦点赞收藏,非常感谢!有不对的地方