LibgGdx - 在AssetManager中加载TrueTypeFont

3

我尝试在我的 LibGdx AssetManager 中加载 .ttf 字体文件,但似乎做不对。我的尝试如下:

在我的 AssetManager 类中:

public static void load(){
//...
//Fonts
FileHandleResolver resolver = new InternalFileHandleResolver();
manager.setLoader(FreeTypeFontGenerator.class, new FreeTypeFontGeneratorLoader(resolver));
manager.setLoader(BitmapFont.class, ".ttf", new FreetypeFontLoader(resolver));
manager.load(fontTest, FreeTypeFontGenerator.class); //fontTest is a ttf-font

然后我在我的屏幕(Screen)中尝试使用它,代码如下:

FreeTypeFontGenerator generator = GdxAssetManager.manager.get(GdxAssetManager.fontTest, FreeTypeFontGenerator.class);
params.size = 50;
font = generator.generateFont(params); //set the bitmapfont to the generator with parameters

这让我遇到了很多奇怪的错误,我甚至不知道要从哪里查找故障。有人知道如何完成这个任务吗?
1个回答

3

是的,那是因为它们没有被加载。这有点像FreeTypeFontGeneratorLoader的一个错误或误导性设计。要使它正常工作,您需要按照以下方式进行操作:

// set the loaders for the generator and the fonts themselves
FileHandleResolver resolver = new InternalFileHandleResolver();
manager.setLoader(FreeTypeFontGenerator.class, new FreeTypeFontGeneratorLoader(resolver));
manager.setLoader(BitmapFont.class, ".ttf", new FreetypeFontLoader(resolver));

// load to fonts via the generator (implicitely done by the FreetypeFontLoader).
// Note: you MUST specify a FreetypeFontGenerator defining the ttf font file name and the size
// of the font to be generated. 
FreeTypeFontLoaderParameter size1Params = new FreeTypeFontLoaderParameter();            
size1Params.fontFileName = "ls-bold.otf";//name of file on disk
size1Params.fontParameters.size = ((int)((Gdx.graphics.getWidth()*0.10f)));         
manager.load("fontWinFail.ttf", BitmapFont.class, size1Params);//BUGGY:We need to append .ttf otherwise wont work...just put any name here and append .ttf MANDATORY(this is the trick)

看到最后一行,你需要将.ttf附加到你选择的任何随机名称中。这就是诀窍。
现在,你要求的示例如下:
BitmapFont                      fontWinFail; 
fontWinFail = manager.get("fontWinFail.ttf", BitmapFont.class);//notice same name used in above segment(NOTE that this is just a name, not the name of the file)         
fontWinFail.setColor(Color.BLACK);

//Then on your render() method
fontWinFail.draw(batch, "hello world", Gdx.graphics.getWidth()*0.5f, Gdx.graphics.getHeight()*0.6f);

哦,我也得在那里设置参数,我明白了。你能给我一个示例代码吗?我想把它分配给一个放置在屏幕上的BitmapFont。就像我问题中的第二个代码示例一样。 - Green_qaue
通常情况下,您会使用名称(在我的情况下为“fontTest”)从AssetManager获取字体,但由于这里的名称是“fontTest.ttf”,我不确定该如何继续。我无法像平常一样使用(GdxAssetManager.fontTest, BitmapFont.class) - Green_qaue
谢谢,顺便说一下,它没有“名称.扩展名”也可以正常工作 :) 但是你帮助我朝着正确的方向前进。 - Green_qaue
很酷,不用谢。你提出的问题非常好且有效,我以前遇到同样的问题时也曾卡住过。 - Gabriel Rodriguez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接