Reputation: 3498
I use following code to generate font in libgdx:
class XFont {
private FreeTypeFontGenerator _generator;
public BitmapFont getFont(String str,int size) {
if (_generator == null) {
_generator = new FreeTypeFontGenerator(Gdx.files.internal("win/msyh.ttf"));
//_generator = new FreeTypeFontGenerator(Gdx.files.absolute("/system/fonts/DroidSansFallback.ttf"));
Gdx.app.log(TAG, "generator"+_generator.toString());
}
return _generator.generateFont(size, str, false);
}
}
when I call :
XFont x = new XFront();
x.getFont("iiiis",11);
raise exception:
java.lang.RuntimeException: Key with name 'i' is already in map.
I work with chinese and japanese.
Upvotes: 1
Views: 1588
Reputation: 73
First, _generator.generateFont(size, str, false)
take str as a string that contains all unique characters that you want to generate bitmap font. I preferred use charset for this. Then you should generate a bitmap font just once. Example:
// in your constants
public static final String FONT_CHARSET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890,./;'[]\\`~!@#$%^&*()_+{}|:\"<>?";
// in your resource loading code
FreeTypeFontGenerator fontGenerator = new FreeTypeFontGenerator(Gdx.files.internal("myFont.ttf"));
BitmapFont myFont = fontGenerator.generateFont(24, FONT_CHARSET, false);
fontGenerator.dipose(); // remember to dispose the generator after used
The FONT_CHARSET
contains all characters in the keyboard, I think it is enough for English texts.
Upvotes: 0
Reputation: 6862
The generateFont()
method takes a string containing the unique characters you'd like to be in the generated font. You then use that generated font to draw a string containing those characters - via font.draw(batch, string, x, y)
.
Note: I'd recommend not generating a new BitmapFont every time you want to draw a String, but instead generate a font with all the characters you will likely use then reuse that BitmapFont.
Upvotes: 1