ubuntu通过SDL_image库显示png图片

1、源

码 

#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

int main() {
    // 初始化SDL
    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        std::cerr << "SDL_Init failed: " << SDL_GetError() << std::endl;
        return -1;
    }

    // 初始化SDL_image
    if ((IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) != IMG_INIT_PNG) {
        std::cerr << "IMG_Init failed: " << IMG_GetError() << std::endl;
        SDL_Quit();
        return -1;
    }

    // 创建窗口
    const int iStart_x = 0;
    const int iStart_y = 0;
    SDL_Window* m_window = SDL_CreateWindow("Image Viewer", iStart_x, iStart_y, 800, 600, SDL_WINDOW_SHOWN);
    if (!m_window) {
        std::cerr << "SDL_CreateWindow failed: " << SDL_GetError() << std::endl;
        IMG_Quit();
        SDL_Quit();
        return -1;
    }

    // 创建SDL渲染器
    SDL_Renderer* m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (!m_renderer) {
        std::cerr << "创建SDL渲染器失败: " << SDL_GetError() << std::endl;
        SDL_DestroyWindow(m_window);
        IMG_Quit();
        SDL_Quit();
        return -1;
    }

    // 加载PNG图片
    SDL_Surface* imageSurface = IMG_Load("startup.png");
    if (!imageSurface) {
        std::cerr << "IMG_Load failed: " << IMG_GetError() << std::endl;
        SDL_DestroyRenderer(m_renderer);
        SDL_DestroyWindow(m_window);
        IMG_Quit();
        SDL_Quit();
        return -1;
    }

    // 创建SDL纹理
    SDL_Texture* imageTexture = SDL_CreateTextureFromSurface(m_renderer, imageSurface);
    if (!imageTexture) {
        std::cerr << "SDL_CreateTextureFromSurface failed: " << SDL_GetError() << std::endl;
        SDL_FreeSurface(imageSurface);
        SDL_DestroyRenderer(m_renderer);
        SDL_DestroyWindow(m_window);
        IMG_Quit();
        SDL_Quit();
        return -1;
    }

    SDL_FreeSurface(imageSurface); // 释放表面

    // 清空渲染器
    SDL_RenderClear(m_renderer);

    // 渲染纹理
    SDL_RenderCopy(m_renderer, imageTexture, NULL, NULL);

    // 刷新屏幕
    SDL_RenderPresent(m_renderer);

    // 处理事件
    SDL_Event event;
    bool quit = false;

    while (!quit) {
        while (SDL_PollEvent(&event) != 0) {
            if (event.type == SDL_QUIT) {
                quit = true;
            }
        }

        SDL_Delay(10); // 小延迟以减少CPU使用率
    }

    // 清理资源
    SDL_DestroyTexture(imageTexture);
    SDL_DestroyRenderer(m_renderer);
    SDL_DestroyWindow(m_window);
    IMG_Quit();
    SDL_Quit();

    return 0;
}
2、安装sdl_image库
sudo apt-get install libsdl2-image-dev
sudo apt-get install libsdl2-dev
3、链接库
LIBS    += -lSDL2 -lSDL2_image