其实没必要说得太复杂...就是读取用户输入啦。
沿用上一篇的代码,加入事件轮询。
环境:SDL2 + VC++2015
下面的代码将打开background.png和event.png,将background平铺背景,将event作为前景呈现。
1 #include <stdexcept> 2 #include <string> 3 #include <iostream> 4 #include "SDL.h" 5 #include "SDL_image.h" 6 7 //屏幕宽度 8 const int SCREEN_WIDTH = 1600; 9 const int SCREEN_HEIGHT = 900; 10 11 //全局窗口和渲染器 12 SDL_Window *window = nullptr; 13 SDL_Renderer *renderer = nullptr; 14 15 //加载图片 16 SDL_Texture* LoadImage(std::string file) 17 { 18 SDL_Texture* tex = nullptr; 19 tex = IMG_LoadTexture(renderer, file.c_str()); 20 if (tex == nullptr) 21 throw std::runtime_error("Failed to load image: " + file + IMG_GetError()); 22 return tex; 23 } 24 25 //将表面应用到渲染器 26 void ApplySurface(int x, int y, SDL_Texture *tex, SDL_Renderer *rend) 27 { 28 SDL_Rect pos; 29 pos.x = x; 30 pos.y = y; 31 SDL_QueryTexture(tex, NULL, NULL, &pos.w, &pos.h); 32 SDL_RenderCopy(rend, tex, NULL, &pos); 33 } 34 35 int main(int argc, char** argv) 36 { 37 //初始化SDL 38 if (SDL_Init(SDL_INIT_EVERYTHING) == -1) 39 { 40 std::cout << SDL_GetError() << std::endl; 41 return 1; 42 } 43 44 //创建窗口 45 window = SDL_CreateWindow("Lesson 4 - Event Driven Programming", 46 SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 47 SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); 48 if (window == nullptr) 49 { 50 std::cout << SDL_GetError() << std::endl; 51 return 2; 52 } 53 54 //创建渲染器 55 renderer = SDL_CreateRenderer(window, -1, 56 SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); 57 if (renderer == nullptr) 58 { 59 std::cout << SDL_GetError() << std::endl; 60 return 3; 61 } 62 63 //创建背景和前景纹理 64 SDL_Texture *background = nullptr, *image = nullptr; 65 try { 66 background = LoadImage("background.png"); 67 image = LoadImage("event.png"); 68 } 69 catch (const std::runtime_error &e) { 70 std::cout << e.what() << std::endl; 71 return 4; 72 } 73 74 bool quit = false; 75 SDL_Event e; 76 //主循环(CPU高占用) 77 while (!quit) 78 { 79 //轮询事件栈e 80 while (SDL_PollEvent(&e)) 81 { 82 //用户关闭窗口 83 if (e.type == SDL_QUIT) quit = true; 84 85 //用户按下键盘 86 if (e.type == SDL_KEYDOWN) quit = true; 87 88 //用户点击鼠标 89 if (e.type == SDL_MOUSEBUTTONDOWN) quit = true; 90 91 //清空渲染器 92 SDL_RenderClear(renderer); 93 94 //在渲染器内平铺背景 95 int bW, bH; 96 SDL_QueryTexture(background, NULL, NULL, &bW, &bH); 97 for (int y = 0; y <= SCREEN_HEIGHT; y += bH) 98 for (int x = 0; x <= SCREEN_WIDTH; x += bW) 99 ApplySurface(x, y, background, renderer); 100 101 102 //在渲染器中央放置前景 103 int iW, iH; 104 SDL_QueryTexture(image, NULL, NULL, &iW, &iH); 105 int x = SCREEN_WIDTH / 2 - iW / 2; 106 int y = SCREEN_HEIGHT / 2 - iH / 2; 107 ApplySurface(x, y, image, renderer); 108 109 //呈现渲染器 110 SDL_RenderPresent(renderer); 111 } 112 } 113 114 //释放资源 115 SDL_DestroyTexture(background); 116 SDL_DestroyTexture(image); 117 SDL_DestroyRenderer(renderer); 118 SDL_DestroyWindow(window); 119 120 SDL_Quit(); 121 122 return 0; 123 }