23. September 2017

SDL2_ttf for Android with TrueType font support

Common library for displaying a text in SDL2 application is SDL2_ttf. The library is a wrapper on FreeType library. It is necessary to add both libraries into a project.

Let’s start with FreeType dependency. Add build.gradle file. Just be aware that there will be many excluded files. The library itself is very huge, and only a fraction of functions is necessary for the application.

sources {
      main {
          jni {
              source {
                  srcDir "src"
                  exclude "autofit"
                  exclude "smooth/smooth.c"
                   // Including this file in build causes duplications, because it includes directly C files
                   exclude "truetype/truetype.c"
                   exclude "type1"
                   exclude "type42"
                   exclude "winfonts"

Adding SDL2_ttf is similar to other libraries like SDL2_jpeg or SDL2_mixer.

SDL2_ttf and FreeType modules should be also registered at settings.gradle:

include ':freetype'
include ':SDL2_ttf'

The first step to displaying text on the screen is to initialize the library and load a font:

#include "SDL_ttf.h"
if (TTF_Init() == -1) {
    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "TTF_Init: %s\n", TTF_GetError());
    return 7;

The next step is to load a font. The file should be stored in app/src/main/assets.

TTF_Font *font = TTF_OpenFont("blazed.ttf", 32);
if (!font) {
                 "Unable to load font: %s\n", TTF_GetError());
    return 8;

The next step is to render a text:

SDL_Color textColor = { 255, 240, 0, 255 };
SDL_Surface* solid = TTF_RenderText_Solid(font, "SDL2 Android Example", textColor);

SDL_Texture* solidTexture = SDL_CreateTextureFromSurface(renderer, solid);
SDL_RenderCopy(renderer, solidTexture, NULL, &dstrect);

Here is the result:

You can find the source code at GitHub in sdl2-android-example repository. Further articles about SDL2 and Android are available under the tag SDL2.