LibGDX is a pretty cool library to write multiplatform games in Java using OpenGL. You can find more about LibGDX here.
I just wanted to share a quick tip to allow the use of custom fonts with the BitmapFont class in LibGDX without having to deal with the usual workaround of having your characters in an image and loading every one of them as if they were regular sprites or textures.
Instead, by loading your font in a BitmapFont object using a FreeTypeFontGenerator you can easily print strings with your fonts without having to load the characters from the texture, calculate offsets and all that stuff which I’ve always found very tedious.
The steps are very easy.
First, you have to download the following folder:
It contains the required libraries to use the freetype package in your core, Android and Desktop projects. Copy the jars in their respective library folders and make sure they’re added to the build paths.
After that, you can use the following snippet to load the fonts. Try to insert it in the same class where you load the resources for your game. Remember to copy the font file in your assets folder.
Declare the fields static in order to allow access from your rendering classes:
public static BitmapFont font; public static final String FONT_FILENAME = "kenvector_future.ttf";
And initialize them in your resource’s load method:
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal(FONT_FILENAME)); FreeTypeFontParameter parameter = new FreeTypeFontParameter(); parameter.size = 30; parameter.flip = true; font = generator.generateFont(parameter); generator.dispose();
Now you can write text by simply calling the following method:
YourAssetsClass.font.draw(batcher, "Your text here", positionX, positionY);
In case the text is printed rotated try to assign the parameter.flip to false.
If you have any question, correction or anything to add to this post, please feel free to leave a comment!