Saturday, February 15, 2014

Libgdx - Generate Bitmap Fonts for Any Screen Size With Minimal Loading Time.

UPDATE: I got some requests, so I created a github repo to make it easy to include this functionality into your project.  This the best way to use this code.

https://github.com/jrenner/gdx-smart-font


This post will show you how to use the FreeTypeFontGenerator (a libgdx extension) and the BitmapFontWriter (included in gdx-tools) to dynamically generate your bitmap font to suit the screen size of the device the app is running on.  We will also optimize the process so that the fonts are only generated if there is no previously generated version found.

FreeTypeFontGenerator is not part of the core libgdx package (not in gdx.jar), to learn how to include it in your project, or use it in general, see this page on the wiki.

BitmapFontWriter is also not part of libgdx core.  It is located in the gdx-tools.jar.  Fortunately, it has little dependencies, which means you can just copy/paste the code of the BitmapFontWriter class directly into your project as a single file, and get it working with little alterations.

Once you get those two things setup, you are ready to go.  Below is the code you need to accomplish font generation/loading.

We get three main benefits from this code:
#1 No need to pre-render font bitmaps using Hiero or some other tool

#2 Fonts are perfectly (more-or-less) sized in proportion to whatever screen size the app is launched with.  Screen-size changes in between launch are also handled. (For mid-game resizing, you would have to do some more work)

#3 By saving the generated fonts to file, we can load from file in subsequent startups where the screen size has not changed (On Android, it should never change).  In my case, this cuts down the loading time for fonts dramatically, make the app start up much snappier.

In my case, where I generate 4 fonts, generating fonts took 3765ms, while loading the pre-generated fonts only took 325ms.  That's more than 3 seconds shaved off of app startup time!

In the images below, notice how despite the different window sizes, the fonts retain the same proportion.  The same effect will occur on Android screens.


1280x720

800x480



First, let's take a look at the code generating the fonts:


Now, let's see how we save the generated fonts to file.  These methods could be directly copied and pasted into your project without alteration.