I'm using OpenGL and SDL to create a window in my program.
How do I use SDL_ttf with an OpenGL window?
For example I want to load a font and render some text. I want to draw the text using an SDL OpenGL surface.
Here's how to do it:
SDL_SetVideoMode()
. Make sure you pass the SDL_OPENGL
flag.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);
Then you can use the texture in OpenGL using glBindTexture()
etc. Make sure to call SDL_GL_SwapBuffers()
when you're done with drawing.