用 SDL2 平铺背景并显示前景
环境:SDL2 + VC++2015
下面的代码将打开background.bmp和image.bmp,将background平铺背景,将image作为前景呈现
1 #include <iostream> 2 #include "SDL.h" 3 4 //屏幕宽度 5 const int SCREEN_WIDTH = 640; 6 const int SCREEN_HEIGHT = 480; 7 8 //全局窗口和渲染器 9 SDL_Window *window = nullptr; 10 SDL_Renderer *renderer = nullptr; 11 12 //加载图片 13 SDL_Texture* LoadImage(std::string file) 14 { 15 SDL_Surface *loadedImage = nullptr; 16 SDL_Texture *texture = nullptr; 17 18 loadedImage = SDL_LoadBMP(file.c_str()); 19 if (loadedImage != nullptr) 20 { 21 texture = SDL_CreateTextureFromSurface(renderer, loadedImage); 22 SDL_FreeSurface(loadedImage); 23 } 24 else 25 std::cout << SDL_GetError() << std::endl; 26 return texture; 27 } 28 29 //将表面应用到渲染器 30 void ApplySurface(int x, int y, SDL_Texture *tex, SDL_Renderer *rend) 31 { 32 SDL_Rect pos; 33 pos.x = x; 34 pos.y = y; 35 SDL_QueryTexture(tex, NULL, NULL, &pos.w, &pos.h); 36 SDL_RenderCopy(rend, tex, NULL, &pos); 37 } 38 39 int main(int argc, char** argv) 40 { 41 //初始化SDL 42 if (SDL_Init(SDL_INIT_EVERYTHING) == -1) 43 { 44 std::cout << SDL_GetError() << std::endl; 45 return 1; 46 } 47 48 //创建窗口 49 window = SDL_CreateWindow("Lesson 2", 50 SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 51 SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); 52 if (window == nullptr) 53 { 54 std::cout << SDL_GetError() << std::endl; 55 return 2; 56 } 57 58 //创建渲染器 59 renderer = SDL_CreateRenderer(window, -1, 60 SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); 61 if (renderer == nullptr) 62 { 63 std::cout << SDL_GetError() << std::endl; 64 return 3; 65 } 66 67 //创建背景和前景纹理 68 SDL_Texture *background = nullptr, *image = nullptr; 69 background = LoadImage("background.bmp"); 70 image = LoadImage("image.bmp"); 71 if (background == nullptr || image == nullptr) 72 return 4; 73 74 //清空渲染器 75 SDL_RenderClear(renderer); 76 77 //在渲染器内平铺背景 78 int bW, bH; 79 SDL_QueryTexture(background, NULL, NULL, &bW, &bH); 80 ApplySurface(0, 0, background, renderer); 81 ApplySurface(bW, 0, background, renderer); 82 ApplySurface(0, bH, background, renderer); 83 ApplySurface(bW, bH, background, renderer); 84 85 //在渲染器中央放置前景 86 int iW, iH; 87 SDL_QueryTexture(image, NULL, NULL, &iW, &iH); 88 int x = SCREEN_WIDTH / 2 - iW / 2; 89 int y = SCREEN_HEIGHT / 2 - iH / 2; 90 ApplySurface(x, y, image, renderer); 91 92 //呈现渲染器 93 SDL_RenderPresent(renderer); 94 SDL_Delay(2000); 95 96 //释放资源 97 SDL_DestroyTexture(background); 98 SDL_DestroyTexture(image); 99 SDL_DestroyRenderer(renderer); 100 SDL_DestroyWindow(window); 101 102 SDL_Quit(); 103 104 return 0; 105 }
彩蛋:
如果窗口变成了1920*1080呢?上面的平铺方法就不够灵活了。试下:
1 int bW, bH; 2 SDL_QueryTexture(background, NULL, NULL, &bW, &bH); 3 for (int y = 0; y <= SCREEN_HEIGHT; y += bH) 4 for (int x = 0; x <= SCREEN_WIDTH; x += bW) 5 ApplySurface(x, y, background, renderer);