[笔记]音视频学习之SDL篇《六》使用SDL_ttf绘制True Type字体

发布时间:2024-01-12 08:23:35

第六节: 使用SDL_ttf绘制True Type字体


准备

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.消息文本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.先根据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;
	}
	//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;
}

总结

TTF_RenderText_Blended

SDL_CreateTextureFromSurface

demo地址

文章来源:https://blog.csdn.net/qq1113673178/article/details/117049406
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。