I am new to LibGDX and trying to make a very simple game. But I soon ran into an issue when using BitmapFont. In my Game class, I load a BitmapFont like so:
private SpriteBatch batch;
private BitmapFont font;
@Override
public void create() {
batch = new SpriteBatch();
font = new BitmapFont(Gdx.files.internal("fonts/PlaypenSans-ExtraLight.ttf"));
this.setScreen(new MainMenuScreen(this));
}
The TTF file was downloaded from Google Fonts. The result was the following error:
Exception in thread "main" com.badlogic.gdx.utils.GdxRuntimeException: Error loading font file: fonts/PlaypenSans-ExtraLight.ttf
at com.badlogic.gdx.graphics.g2d.BitmapFont$BitmapFontData.load(BitmapFont.java:717)
at com.badlogic.gdx.graphics.g2d.BitmapFont$BitmapFontData.<init>(BitmapFont.java:485)
at com.badlogic.gdx.graphics.g2d.BitmapFont.<init>(BitmapFont.java:116)
at com.badlogic.gdx.graphics.g2d.BitmapFont.<init>(BitmapFont.java:109)
at com.ssage.pong.Pong.create(Pong.java:18)
at com.badlogic.gdx.backends.lwjgl3.Lwjgl3Window.initializeListener(Lwjgl3Window.java:416)
at com.badlogic.gdx.backends.lwjgl3.Lwjgl3Window.update(Lwjgl3Window.java:366)
at com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application.loop(Lwjgl3Application.java:192)
at com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application.<init>(Lwjgl3Application.java:166)
at com.ssage.pong.desktop.DesktopLauncher.main(DesktopLauncher.java:16)
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Invalid padding.
at com.badlogic.gdx.graphics.g2d.BitmapFont$BitmapFontData.load(BitmapFont.java:500)
I got the same error with other TTF files.
Using BitmapFont with the default constructor (so the default font) does work. I can't find anything about the "invalid padding error" online.
A BitmapFont
is a class that wraps a bitmap-font, which is a text document describing where in a image each character is located (for example the default.fnt file from libGDX), it does not load TTF files.
If you want to use TTF files in your project, you should enable the freetype extension (you can pick it when you create your libGDX project), and then use the FreeTypeFontGenerator
to generate a BitmapFont
on the fly.
The libGDX freetype page has some good examples on how to do this, but essentially you
FreeTypeFontGenerator
passing the TTF file as a constructor argument.FreeTypeFontParameter
object and set things like size on it.generateFont
on the FreeTypeFontGenerate
object passing in the parameters, this will return a BitmapFont
.