问题描述
我正在使用 OpenGL 和 SDL 在我的程序中创建一个窗口.
I'm using OpenGL and SDL to create a window in my program.
如何在 OpenGL 窗口中使用 SDL_ttf?
How do I use SDL_ttf with an OpenGL window?
例如,我想加载字体并渲染一些文本.我想使用 SDL OpenGL 表面绘制文本.
For example I want to load a font and render some text. I want to draw the text using an SDL OpenGL surface.
推荐答案
方法如下:
- 初始化 SDL 和 SDL_ttf,并使用
SDL_SetVideoMode()
创建一个窗口.确保您传递了SDL_OPENGL
标志. - 初始化您的 OpenGL 场景(
glViewport()
、glMatrixMode()
等). 使用 SDL_ttf 渲染您的文本,例如
TTF_RenderUTF8_Blended()
.渲染函数返回一个 SDL_surface,您必须通过将指向数据(surface->pixels
)的指针以及数据格式传递给 OpenGL,将其转换为 OpenGL 纹理.像这样:
- Initialize SDL and SDL_ttf, and create a window using
SDL_SetVideoMode()
. Make sure you pass theSDL_OPENGL
flag. - Initialize your OpenGL scene (
glViewport()
,glMatrixMode()
etc.). Render your text with SDL_ttf using e.g.
TTF_RenderUTF8_Blended()
. The render functions return an SDL_surface, which you have to convert into an OpenGL texture by passing a pointer to the data (surface->pixels
) to OpenGL as well as the format of the data. Like this:
colors = surface->format->BytesPerPixel;
if (colors == 4) { // alpha
if (surface->format->Rmask == 0x000000ff)
texture_format = GL_RGBA;
else
texture_format = GL_BGRA;
} else { // no alpha
if (surface->format->Rmask == 0x000000ff)
texture_format = GL_RGB;
else
texture_format = GL_BGR;
}
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, colors, surface->w, surface->h, 0,
texture_format, GL_UNSIGNED_BYTE, surface->pixels);
然后您可以使用 glBindTexture()
等在 OpenGL 中使用纹理.确保在完成绘图后调用 SDL_GL_SwapBuffers()
.
Then you can use the texture in OpenGL using glBindTexture()
etc. Make sure to call SDL_GL_SwapBuffers()
when you're done with drawing.
这篇关于在 OpenGL 中使用 SDL_ttf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!