准备工作
背景图和居中图
背景图 320*240
居中图
SDL窗口坐标系
左上角为(0,0)坐标
初始化和创建窗口
//Start up SDL and make sure it went ok
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
logSDLError(std::cout, "SDL_Init");
return 1;
}
//Setup our window and renderer
SDL_Window *window = SDL_CreateWindow("Lesson 2", 100, 100, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (window == nullptr) {
logSDLError(std::cout, "CreateWindow");
SDL_Quit();
return 1;
}
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == nullptr) {
logSDLError(std::cout, "CreateRenderer");
cleanup(window);
SDL_Quit();
return 1;
}
载入两张图片
//The textures we'll be using
const std::string resPath = getResourcePath("02sdl_learn");
SDL_Texture *background = loadTexture(resPath + "background.bmp", renderer);
SDL_Texture *image = loadTexture(resPath + "image.bmp", renderer);
//Make sure they both loaded ok
if (background == nullptr || image == nullptr) {
cleanup(background, image, renderer, window);
SDL_Quit();
return 1;
}
绘制背景图和居中图片
背景图是长320宽240,窗口是长640*宽480,正好可以画4个
执行四次 分别从
(0,0),(320,0),(0,240),(320,240)位置开始绘制。
renderTexture(background, renderer, 0, 0);
renderTexture(background, renderer, bW, 0);
renderTexture(background, renderer, 0, bH);
renderTexture(background, renderer, bW, bH);
A sleepy rendering loop, wait for 3 seconds and render and present the screen each time
//for (int i = 0; i < 3; ++i) {
//Clear the window
SDL_RenderClear(renderer);
//Get the width and height from the texture so we know how much to move x,y by
//to tile it correctly
int bW, bH;
SDL_QueryTexture(background, NULL, NULL, &bW, &bH);
//We want to tile our background so draw it 4 times
renderTexture(background, renderer, 0, 0);
renderTexture(background, renderer, bW, 0);
renderTexture(background, renderer, 0, bH);
renderTexture(background, renderer, bW, bH);
//Draw our image in the center of the window
//We need the foreground image's width to properly compute the position
//of it's top left corner so that the image will be centered
int iW, iH;
SDL_QueryTexture(image, NULL, NULL, &iW, &iH);
int x = SCREEN_WIDTH / 2 - iW / 2;
int y = SCREEN_HEIGHT / 2 - iH / 2;
renderTexture(image, renderer, x, y);
//Update the screen
SDL_RenderPresent(renderer);
//Take a quick break after all that hard work
SDL_Delay(10000);
/*}*/
退出
cleanup(background, image, renderer, window);
SDL_Quit();
效果图
总结
平铺主要通过计算窗口宽是图片的宽的n = winHeight / picHeight倍,高是m = winWidth / picWidth 倍,
从而确定最终画出n*m个背景图平铺填满.