SDL2 显示图片

在上篇的项目中,设置好了SDL2的头文件和库文件,本篇使用SDL2_image 显示图片。

1. 准备库

该库的下载地址: SDL2_image-devel-2.8.2-VC.zip

下载后解压:

 2. 配置头文件、库文件

  • Add the include path of SDL_image to the project
  • Add the lib path of SD_image to the project
  • Add the new lib entry SDL2_image.lib

 3. 复制DLL文件到目标文件夹

  • SDL2_image.dll – DLL of SDL_image
  • libjpeg-9.dll – DLL of libjpeg (add if you want to read JPEG images)
  • libpng16-16.dll – DLL of libpng (add if you want to read PNG images)
  • libtiff-5.dll – DLL of libtiff (add if you want to read TIFF images)
  • libwebp-7.dll – DLL of libwebp (add if you want to read WEBP images)
  • zlib1.dll – DLL of zlib (add if you want to read png images)

4. 准备图片

自己准备个png图片吧,我这里用的是girl.png,路径在下面的代码里。

5. 显示图片的代码如下

 1 // SdlTest.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
 2 //
 3 
 4 #include <iostream>
 5 #include "SDL.h"
 6 #include "SDL_image.h"
 7 
 8 int main(int argc, char* argv[]) {
 9     if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) < 0) {
10         std::cout << "Error SDL2 Initialization : " << SDL_GetError();
11         return 1;
12     }
13 
14     if (IMG_Init(IMG_INIT_PNG) == 0) {
15         std::cout << "Error SDL2_image Initialization";
16         return 2;
17     }
18 
19     SDL_Window* window = SDL_CreateWindow("First program", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
20     if (window == NULL) {
21         std::cout << "Error window creation";
22         return 3;
23     }
24 
25     SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
26     if (renderer == NULL) {
27         std::cout << "Error renderer creation";
28         return 4;
29     }
30 
31     SDL_Surface* lettuce_sur = IMG_Load("D:\\Temp\\SdlTest\\x64\\Debug\\girl.png");
32     if (lettuce_sur == NULL) {
33         std::cout << "Error loading image: " << IMG_GetError();
34         return 5;
35     }
36 
37     SDL_Texture* lettuce_tex = SDL_CreateTextureFromSurface(renderer, lettuce_sur);
38     if (lettuce_tex == NULL) {
39         std::cout << "Error creating texture";
40         return 6;
41     }
42 
43     SDL_FreeSurface(lettuce_sur);
44 
45     while (true) {
46         SDL_Event e;
47         if (SDL_PollEvent(&e)) {
48             if (e.type == SDL_QUIT) {
49                 break;
50             }
51         }
52 
53         SDL_RenderClear(renderer);
54         SDL_RenderCopy(renderer, lettuce_tex, NULL, NULL);
55         SDL_RenderPresent(renderer);
56     }
57 
58     SDL_DestroyTexture(lettuce_tex);
59     SDL_DestroyRenderer(renderer);
60     SDL_DestroyWindow(window);
61     IMG_Quit();
62     SDL_Quit();
63 
64     return 0;
65 }
66  

代码不多, 这里不再解释了,原文中有一定的解释,可以参照:

Display an image with SDL_image, free tutorial (glusoft.com)

上一篇忘记写原文出处了, 这里补上:
Install SDL on Windows, free tutorial (glusoft.com)
6. 运行效果

会打开一个窗口,里面显示我们准备的图片:

 

 

 
posted @ 2024-06-26 21:24  乁卬杨  阅读(49)  评论(0编辑  收藏  举报