准备
SDL_ttf库
配置dll和lib 我就不细说了可以模仿我demo用cmake配置
头文件放SDL.h同一个目录
sample.ttf SourceSansPro-Regular 字体文件
目的
使用ttf字体文件 进行文字的渲染
也就是使用ttf文件 自定义文字的字体显示
主要绘制一行"Shiver Is Best Awesome"消息文本
初始化,创建窗口、渲染器等
TTF_Init() tif初始化
//Start up SDL and make sure it went ok
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
logSDLError(std::cout, "SDL_Init");
return 1;
}
//Also need to init SDL_ttf
if (TTF_Init() != 0) {
logSDLError(std::cout, "TTF_Init");
SDL_Quit();
return 1;
}
//Setup our window and renderer
SDL_Window* window = SDL_CreateWindow("Lesson 6", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (window == nullptr) {
logSDLError(std::cout, "CreateWindow");
TTF_Quit();
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);
TTF_Quit();
SDL_Quit();
return 1;
}
1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.
载入字体内容并绘制
绘制文字需要:
1.消息文本message
2.字体文件fontFile
3.字体颜色color
4.字体大小fontSize
const std::string resPa
th = getResourcePath("Lesson6");
//We'll render the string "TTF fonts are cool!" in white
//Color is in RGB format
SDL_Color color = { 255, 255, 255, 255 };
SDL_Texture* image = renderText("Shiver is best Aswsome", "..\\..\\res\\06sdl_learn\\sample.ttf", color, 64, renderer);
if (image == nullptr) {
cleanup(image, renderer, window);
TTF_Quit();
SDL_Quit();
return 1;
}
1.2.3.4.5.6.7.8.9.10.11.12.
绘制字体过程:
1.打开字体文件
2.先根据render,message,color 创建Surface
3.使用Surface创建Texture
SDL_Texture* renderText(const std::string& message, const std::string& fontFile, SDL_Color color,
int fontSize, SDL_Renderer* renderer)
{
//Open the font
TTF_Font* font = TTF_OpenFont(fontFile.c_str(), fontSize);
if (font == nullptr) {
logSDLError(std::cout, "TTF_OpenFont");
return nullptr;
}郑州哪家精神病医院好http://www.juenpt.com/
//We need to first render to a surface as that's what TTF_RenderText returns, then
//load that surface into a texture
SDL_Surface* surf = TTF_RenderText_Blended(font, message.c_str(), color);
if (surf == nullptr) {
TTF_CloseFont(font);
logSDLError(std::cout, "TTF_RenderText");
return nullptr;
}
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surf);
if (texture == nullptr) {
logSDLError(std::cout, "CreateTexture");
}
//Clean up the surface and font
SDL_FreeSurface(surf);
TTF_CloseFont(font);
return texture;
}