Search code examples
fontssdlsdl-2truetypesdl-ttf

How to render fonts and text with SDL2 efficiently?


Saw this post here about using SDL_ttf to render text in a game. However that approach requires calling SDL_CreateTextureFromSurface(), along with the SDL_FreeSurface() and SDL_DestroyTexture() every single frame.

Is creating textures (and probably subsequently having to send them to the GPU) every frame something that can significally impact my performance?

would it be wiser to use SDL_ttf only to create a texture with my whole rendered charset and then to blit from there myself, character by character?

Edit: I'm looking to render simple monospace fonts in US-English (basic ASCII) only.


Solution

  • Yes, creating textures every frame can affect performance. Also, rasterizing TrueType fonts to SDL_Surfaces (as SDL_ttf does) every frame can affect performance.

    I recommend SDL_FontCache (full disclosure: I'm the author). It uses SDL_ttf and caches the resulting glyphs in textures so you don't have to do it all yourself:
    https://github.com/grimfang4/SDL_FontCache