我无法在 OpenGL 和 SDL2.0 中绘制 TTF 字体。
我记得在 SDL 版本 2 之前我没有遇到任何问题,但似乎缺少有关该主题的文档,可能是由于新标准。
我已经包含了下面的代码,以显示我在做什么。
这段代码效率很低,因为我每帧都重新创建纹理,如果复制+粘贴,请考虑到这一点:)
void main_render() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Set our color back to white (Full texture color)
glColor3f(1.0f, 1.0f, 1.0f);
mainCamera->perspective();
mainCamera->translate();
//Load the font
TTF_Font *font = TTF_OpenFont("../resource/font.ttf", 10);
if (font == nullptr) {
std::cout << "TTF_OpenFont error: " << std::endl;
return;
}
//Render font to a SDL_Surface
SDL_Color color = {0,0,255,80};
SDL_Surface *surface = TTF_RenderText_Blended(font, "Hi!", color);
if (surface == nullptr) {
TTF_CloseFont(font);
std::cout << "TTF_RenderText error: " << std::endl;
return;
}
//Create a SDL_Texture * from the surface
SDL_Texture * text = SDL_CreateTextureFromSurface(fontRender, surface);
if (text == nullptr){
std::cout << "SDL_CreateTextureFromSurface error: " << std::endl;
return;
}
//Bind the SDL_Texture in OpenGL
SDL_GL_BindTexture(text, NULL, NULL);
//Draw the SDL_Texture * as a Quad
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS); {
glTexCoord2d(0, 0); glVertex3f(0, 0, 0);
glTexCoord2d(1, 0); glVertex3f(0 + surface->w, 0, 0);
glTexCoord2d(1, 1); glVertex3f(0 + surface->w, 0 + surface->h, 0);
glTexCoord2d(0, 1); glVertex3f(0, 0 + surface->h, 0);
} glEnd();
glDisable(GL_TEXTURE_2D);
//Cleanup
TTF_CloseFont(font);
SDL_DestroyTexture(text);
SDL_FreeSurface(surface);
//Swap the buffers to refresh the window
mainWindow->swap_buffers();
}