在 LibGdx 中管理位图字体资源

Managing Bitmap Font assets in LibGdx

我可以使用以下代码加载位图字体:

BitmapFont font= new BitmapFont( 
            Gdx.files.internal( "Fonts/MyFont.fnt" ),
            Gdx.files.internal( "Fonts/MyFont.png" ), 
            false );

但我正在尝试实施 AssetManager。所以我用以下代码重新编码了该片段:

AssetManager assetManager = new AssetManager();
assetManager.load( "Fonts/MyFont.fnt", BitmapFont.class );
assetManager.load( "Fonts/MyFont.png", Texture.class );
assetManager.finishLoading();
BitmapFont font = assetManager.get( "Fonts/MyFont.fnt" );

当然如果失败了。对 finishLoading() 方法的调用返回了一条消息,指示:

Couldn't load dependencies of asset: "Fonts/MyFont.fnt"

好的。这是有道理的,因为我没有对纹理做任何事情。那么如何将纹理文件作为依赖项传递呢? github.com/libgdx/libgdx/wiki/Managing-your-assets 说:

BitmapFontLoader is a good example of an asynchronous loader that also has dependencies that need to be loaded before the actual asset can be loaded (in that case it's the texture storing the glyphs). Again, you can do pretty much anything with this.

好吧!我猜他们假设,“......如果你只知道怎么做!”但是,他们的示例并没有说明如何——事实上,他们的示例几乎说明了我所写的内容。所以,我很难过。所有 Google 似乎都能找到关于如何处理 TTF 字体的示例,但对于常规的旧位图字体却一无所获。

有没有人有解决此错误的示例。百万感谢!

当您使用 AssetManager 加载 BitmapFont 时,使用的是 BitmapFontLoader class。在 Libgdx api 文档中说 (api)

AssetLoader for BitmapFont instances. Loads the font description file (.fnt) asynchronously, loads the Texture containing the glyphs as a dependency.

字形纹理作为字体的依赖项自动加载。然而,要知道加载哪个文件作为纹理,它会在 .fnt 文件中检查纹理的位置。

我怀疑不使用AssetManager加载字体成功的原因是你手动添加了字体的Texture作为参数。

BitmapFont font= new BitmapFont( 
        Gdx.files.internal( "Fonts/MyFont.fnt" ),
        Gdx.files.internal( "Fonts/MyFont.png" ), // This lets it know what texture to use
        false );

另一方面,当您使用 AssetManager 时,它无法 find/load 纹理依赖。要解决此问题,请打开 .fnt 文件并确保 file="something.png" 指向您的字体纹理字形。 (它必须与 png 的名称相同。在您的情况下 file="MyFont.png"

这有望解决您的问题。

我久经考验的代码:

    AssetManager manager = new AssetManager();
    manager.load("fonts/MyFont.fnt", BitmapFont.class);
    manager.finishLoading();

    font = manager.get("fonts/MyFont.fnt", BitmapFont.class);

MyFont.fnt 文件的摘录:

info face=font size=54 bold=0 italic=0 charset= unicode= stretchH=100 smooth=1
aa=1 padding=2,2,2,2 spacing=0,0 outline=0 common lineHeight=50 base=43 scaleW=243
scaleH=511 pages=1 packed=0
page id=0 file="MyFont.png"  <-- The important part

希望这能解决您的问题!


另请注意,当我测试 AssetManager 时,我注意到它仅在 .fnt 为基本文本时加载。当我尝试使用使用标签(如 html)的 .fnt 文件时,纹理加载失败。我使用 littera 生成了我用于测试的位图字体。