前言
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;
注意:本文為個人記錄,新手照搬可能會出現各種問題,請謹慎使用
碼字不易,如果這篇博客對你有幫助,麻煩點贊收藏,非常感謝!有不對的地方