如何用LibGDX BitmapFont修改字体大小?方案无效且代码报错
问题分析与解决
1. 直接加载TTF字体无效的原因
你用new BitmapFont(Gdx.files.internal("HARLOWSI.TTF"))是错误的——BitmapFont的这个构造函数只能加载.fnt格式的位图字体配置文件,并非用来直接加载TTF矢量字体。你看到的“没效果”本质是根本没成功加载指定的TTF,程序一直在用默认字体,所以调用setScale()或getData().setScale()自然不会有预期的字体大小变化。
2. 语法错误的原因
你代码里parameter.size = 12;写在类的成员变量声明区域,Java语法不允许在这个位置直接执行赋值语句(变量初始化时的赋值除外)。必须把这个赋值逻辑放到构造函数、初始化块或者方法里。
3. 正确实现字体大小设置的代码
下面是修正后的Points类,用FreeTypeFontGenerator正确生成指定大小的BitmapFont:
package com.mygdx.game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter; public class Points { private String name; private int quantity; private Texture icon; private BitmapFont font; public Points(String name, int quantity, Texture icon) { this.name = name; this.quantity = quantity; this.icon = icon; // 初始化字体生成器和参数 FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("HARLOWSI.TTF")); FreeTypeFontParameter parameter = new FreeTypeFontParameter(); parameter.size = 12; // 这里设置字体大小,放在构造函数内就不会报错了 // 生成指定大小的BitmapFont font = generator.generateFont(parameter); // 用完generator立即释放,避免内存泄漏 generator.dispose(); } // getter和setter方法保持不变 public String getName() { return name; } public void setName(String name) { this.name = name; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public Texture getIcon() { return icon; } public void setIcon(Texture icon) { this.icon = icon; } public void add(int added) { this.setQuantity(this.quantity + added); } public void substract(int substracted) { this.add(-substracted); } public void show(SpriteBatch batch) { batch.draw(this.icon, 10, 890 - this.icon.getHeight()); this.font.draw(batch, "Points : " + String.valueOf(this.quantity), 20 + this.icon.getWidth(), 890 - this.icon.getHeight()); } public void show(SpriteBatch batch, int x, int y) { batch.draw(this.icon, x, y); // 调整坐标适配传入的参数,避免固定值导致显示错位 this.font.draw(batch, "Points : " + String.valueOf(this.quantity), x + 20 + this.icon.getWidth(), y + this.icon.getHeight()); } // 对象销毁时释放字体资源 public void dispose() { font.dispose(); } }
额外注意事项
- 用FreeType生成字体后,必须调用
generator.dispose()和font.dispose()释放资源,避免内存泄漏。 - 如果需要动态调整字体大小,不建议直接用
setScale()(会导致字体模糊),最好提前生成多个尺寸的字体备用,或重新用FreeType生成对应大小的BitmapFont。
内容的提问来源于stack exchange,提问作者arthur moiret
相关产品推荐
相关产品推荐

