65.9K
CodeProject is changing. Read more.
Home

Higher Quality Small Font Size in Libgdx

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

Sep 25, 2017

CPOL

1 min read

viewsIcon

5350

Higher quality small font size in Libgdx

So continuing from my previous post about using a True Font Type for LibGDX, there’s a problem you might notice that will happen when your font size is too small. The quality suffers!

Check this out for example:

bad vs good

On the left side, you can see that the font looks horrible and you can’t make anything out. On the right side, the image looks exactly the same but it’s higher quality.

So what’s the difference? The answer: the font size.

So when you first start working with the FreeTypeFontGenerater, you might think that if you want a different font size, you just change the parameter.size to whatever value you want.

Turns out if you have a large font size, then everything will be fine, but if you want to create a smaller font size, you’re going to run into problems.

So what’s the solution?

It turns out what you have to do is to create larger font-size and then scale it down. This way, you’ll have a higher quality font at the same size.

Check out this code snippet for an example of how this is done with an actor class (or how you might do this in a Scene renderer):

public class HeaderTextUI extends Actor {
    private String text;
    private BitmapFont bitmapFont;

    public HeaderTextUI(String text, BitmapFont bitmapFont) {
        this.text = text;
        this.bitmapFont = bitmapFont;
        bitmapFont.getData().setScale(0.4f, 0.4f);
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        bitmapFont.draw(batch, text, getX(), getY());
    }
}

Notice how we were passed in a bitmapFont? That was loaded from our AssetManager that we initialized at the beginning of the game. Here’s a snippet of the code that creates the BitmapFont object we’re using.

FreetypeFontLoader.FreeTypeFontLoaderParameter headerFont = 
                new FreetypeFontLoader.FreeTypeFontLoaderParameter();
headerFont.fontFileName = "font/turtles.
headerFont.fontParameters.size = 
headerFont.fontParameters.color = new Color(1, 150f/255f, 0, 
headerFont.fontParameters.borderWidth = 
headerFont.fontParameters.borderColor = new Color(194f/255f, 94f/255f, 0, 
assetManager.load(Constants.FONT_HEADER_GENERAL, BitmapFont.class, headerFont);

I hope you’ve found this helpful and that it has allowed you to create higher quality small font size texts!

The post Higher Quality Small Font Size in Libgdx appeared first on Coding Chronicles.