打印完图片,是时候打印文字了。这里引用了SDL的字体扩展库,SDL2_ttf.lib,需要包含相应的头文件。
环境:SDL2 + VC++2015
下面的代码将在窗口打印一段文字,并对相应的操作做出响应。
这次把错误处理给精简掉了,代码看起来更清爽。
1 #include <iostream> 2 #include "SDL.h" 3 #include "SDL_ttf.h" 4 5 int main(int argc, char** argv) 6 { 7 //屏幕宽度 8 const int SCREEN_WIDTH = 680; 9 const int SCREEN_HEIGHT = 400; 10 //初始化SDL 11 SDL_Init(SDL_INIT_EVERYTHING); 12 //初始化字体库 13 TTF_Init(); 14 //创建窗口 15 SDL_Window *window = SDL_CreateWindow("Font Test", 16 SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 17 SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); 18 //创建渲染器 19 SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 20 SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); 21 22 //打开字体 23 TTF_Font *font = TTF_OpenFont("XHei.TTC", 30); 24 //文本转表面 25 SDL_Color color = { 255, 255, 255 }; 26 SDL_Surface *surf = TTF_RenderText_Blended(font, "Cool, Cooler, Coolest!", color); 27 //表面转纹理 28 SDL_Texture *text = SDL_CreateTextureFromSurface(renderer, surf); 29 //释放资源 30 SDL_FreeSurface(surf); 31 TTF_CloseFont(font); 32 33 bool quit = false; 34 SDL_Event e; 35 //主循环 36 while (!quit) 37 { 38 //事件栈轮询 39 while (SDL_PollEvent(&e)) 40 { 41 //按右上角的X或点鼠标退出 42 if (e.type == SDL_QUIT || e.type == SDL_MOUSEBUTTONDOWN) quit = true; 43 //清空渲染器 44 SDL_RenderClear(renderer); 45 //渲染字体 46 SDL_RenderCopy(renderer, text, NULL, NULL); 47 //呈现渲染器 48 SDL_RenderPresent(renderer); 49 } 50 } 51 52 //释放资源 53 SDL_DestroyTexture(text); 54 SDL_DestroyRenderer(renderer); 55 SDL_DestroyWindow(window); 56 57 SDL_Quit(); 58 59 return 0; 60 }
时间: 2024-10-15 01:10:05