Search code examples
javaandroidfontslibgdx

Load BitmapFont Android LibGdx


I am trying to use BitmapFont from file 1.ttf (LibGdx application for android). However wherever I put this file, I obtain an error that it is not found. Here is my code:

BitmapFont font = new BitmapFont(Gdx.files.internal("1.ttf"), false);

Where should I put this font file? Or what should I change?


Solution

  • You can't create BitmapFont directly using .ttf file. You need to use Gdx freetype in your project.

    Since gdx-freetype is an extension, it is not included in your LibGDX project by default so put gdx-freetype in your project. If your project using gradle for dependency management, add required artifacts in your root build.gradle file.

    After injection of required dependency, keep your .ttf file inside assets folder of android module, that will share with other module using config.

    Generate BitmapFont using FreeTypeFontGenerator in this way :

    FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("1.ttf"));
    FreeTypeFontParameter parameter = new FreeTypeFontParameter();
    parameter.size = 12;
    BitmapFont font12 = generator.generateFont(parameter); // font size 12 pixels
    generator.dispose(); // don't forget to dispose to avoid memory leaks!