用SDL展示一张JPG图片


#include <iostream>
#include "SDL2/SDL.h"
#include "SDL2_image/SDL_image.h"
#include "demo_sdl.h"

using namespace std;

const int WIDTH = 1000;
const int HEIGHT = 600;
void showImage() {
    if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
        cout << "初始化失败" << endl;
        return;
    }
    SDL_Window *window = SDL_CreateWindow("Show Image",
                                          SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                          WIDTH, HEIGHT, SDL_WINDOW_SHOWN);
    if (window == nullptr) {
        cout << "创建Window失败:" << SDL_GetError() << endl;
        return;
    }

    SDL_Renderer *renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_ACCELERATED);
    if (renderer == nullptr) {
        cout << "创建Renderer失败:" << SDL_GetError() << endl;
        return;
    }

    SDL_Surface *image = IMG_Load("/Volumes/T5/CppPractice/renderer-dog/res/demo.jpg");
    if (!image){
        cout << "加载图片失败:" << SDL_GetError() << endl;
        return;
    }

    // 如果使用硬件加速,则必须将Surface转换成Texture
    SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer,image);
    SDL_FreeSurface(image);

    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer,texture, nullptr, nullptr);
    SDL_RenderPresent(renderer);

    SDL_Event windowEvent;
    while (true){
        if (SDL_PollEvent(&windowEvent)){
            if (windowEvent.type == SDL_QUIT){
                std::cout << "终止程序" << std::endl;
                break;
            }
        }
    }
    SDL_DestroyRenderer(renderer);
    SDL_DestroyTexture(texture);
    SDL_DestroyWindow(window);
    SDL_Quit();
}

基本步骤

  1. 初始化
  2. 创建Window
  3. 创建Renderer,用于在Window上渲染内容
  4. 创建Surface,Surface其实就是像素的载体
  5. 如果需要使用硬件加速,需要将Surface转换成Texture
  6. 清除Renderer内容,并使用Renderer的Copy功能将texture内容复制到屏幕的指定区域
  7. 指定当前的Renderer.
  8. 事件监听
  9. 销毁各种对象

遇到的问题

  • MacOS安装的SDL2_image库打开时提示安全提示

    解决方案:

    sudo spctl --master-disable

源码

https://github.com/jiangkang/renderer-dog


文章作者: 姜康
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 姜康 !
评论
  目录