下面是“C++小游戏tankwar之界面绘制的详细过程”的完整攻略。
界面绘制的流程
- 初始化SDL
在使用SDL进行图形绘制前,需要进行SDL库的初始化。调用SDL_Init
函数即可进行初始化。同时还需要对SDL图形界面进行设置,包括窗口大小、窗口名称等。
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window = SDL_CreateWindow("TankWar", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
- 加载图片素材
将需要用到的图片素材加载进内存中,方便后面渲染到屏幕上。调用SDL_LoadBMP
函数可将位图文件加载进SDL_Surface数据结构中。
SDL_Surface* playerImg = SDL_LoadBMP("player.bmp");
- 将图片素材渲染到屏幕上
调用SDL_RenderCopy
函数将图片素材渲染到屏幕上。该函数需要传递三个参数,分别是SDL_Renderer对象、SDL_Texture对象和SDL_Rect对象。其中,SDL_Texture对象可以通过调用SDL_CreateTextureFromSurface
函数将SDL_Surface对象转化为。
SDL_Texture* playerTexture = SDL_CreateTextureFromSurface(renderer, playerImg);
SDL_Rect playerPos = {100, 100, PLAYER_WIDTH, PLAYER_HEIGHT};
SDL_RenderCopy(renderer, playerTexture, NULL, &playerPos);
- 绘制文本
在屏幕上绘制文本需要用到TTF库。与SDL初始化类似,需要对TTF库进行初始化。然后调用TTF_OpenFont
函数打开需要使用的字体文件,然后再调用TTF_RenderUTF8_Solid
函数即可将需要显示的文字渲染进SDL_Surface上,最后再将SDL_Surface渲染到屏幕上即可。
TTF_Init();
TTF_Font* font = TTF_OpenFont("Heavy.ttf", 20);
SDL_Color white = {255, 255, 255};
SDL_Surface* surfaceMessage = TTF_RenderUTF8_Solid(font, "Game Over!", white);
SDL_Rect messageRect = {200, 200, surfaceMessage->w, surfaceMessage->h};
SDL_Texture* message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);
SDL_RenderCopy(renderer, message, NULL, &messageRect);
示例
下面分别给出路径为./images/
的图片素材绘制及TTF字体绘制的示例代码:
图片素材绘制示例代码
SDL_Surface* playerImg = SDL_LoadBMP("./images/player.bmp");
SDL_Texture* playerTexture = SDL_CreateTextureFromSurface(renderer, playerImg);
SDL_Rect playerPos = {100, 100, PLAYER_WIDTH, PLAYER_HEIGHT};
SDL_RenderCopy(renderer, playerTexture, NULL, &playerPos);
TTF字体绘制示例代码
TTF_Init();
TTF_Font* font = TTF_OpenFont("./fonts/Heavy.ttf", 20);
SDL_Color white = {255, 255, 255};
SDL_Surface* surfaceMessage = TTF_RenderUTF8_Solid(font, "Game Over!", white);
SDL_Rect messageRect = {200, 200, surfaceMessage->w, surfaceMessage->h};
SDL_Texture* message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);
SDL_RenderCopy(renderer, message, NULL, &messageRect);
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C++小游戏tankwar之界面绘制的详细过程 - Python技术站