TrueType Fonts in LibGDX

Posted on Thu, 14 Jul 2016 in Java

LibGDX is a beautiful library. It's easy to use. However some aspects of it isn't so clean. Dealing with fonts is an example of such aspects. I spent hours before I found reasonable solution that makes fonts looks good on an Android and on a desktop.

Forget about bitmap fonts. It takes a huge amount of time to fit sizes and prepare fixtures that look good on any device. I don't know any reason to do it. Use TrueType Fonts instead.

I know that using BitMapFont with distance field is recommended way. But you have to do a lot of work before you get reasonable results. Reasonable but not perfect.

Using TTF gives a great result. There is one trick. You should use screen independent size for the font. There is the snippet in Kotlin how to prepare, convert, and add to skin TTF.

class MyGame() : Game() {

    var skin : Skin = Skin()

    override fun create() {
        val generator = FreeTypeFontGenerator(Gdx.files.internal("Roboto-Regular.ttf"))

        val param = FreeTypeFontGenerator.FreeTypeFontParameter()

        val ratio = Gdx.graphics.width / 960f

        param.size = (48 * ratio).toInt()
        val robotoFont = generator.generateFont(param)

        skin.addRegions(TextureAtlas(Gdx.files.internal("skin.atlas")))
        skin.add("normaltext", robotoFont)

        skin.load(Gdx.files.internal("skin.json"))
    }

    override fun dispose() {
        super.dispose()
        skin.dispose()
    }
}

As you see It's very easy. It works perfect. I don't notice any performance drops.

---
Got a question? Hit me on Twitter: avkorablev