有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java自定义可单击字体

我正在尝试为我的游戏制作一个自定义的、可点击的字体(对于菜单,如:PLAY->;goes to playscreen),我尝试过使用FreeType,但当我用它制作新文本时,它会在安卓上占用大量内存。你能给我一个正确的方法来创建一个可点击的文本。ttf文件?我是这样做的:

我有一个盒子类:

public class Box {

   protected float x;
   protected float y;
   protected float width;
   protected float height;

   public boolean contains(float x, float y) {
      return x > this.x - width / 2 &&
            x < this.x + width / 2 &&
            y > this.y - height / 2 &&
            y < this.y + height / 2;
   } 
}

然后Text类及其扩展框,因此当我创建新文本时,我可以调用。包含(x,y),因此我可以使文本可点击:

public class Texts  extends Box{

   private String text;
   private int size;
   private float density;
   private int dpSize;
   private BitmapFont font;
   private FreeTypeFontGenerator generator;
   private FreeTypeFontParameter parameter;

   public Texts(String text, int size, float x ,float y){
      this.text = text;
      this.size = size;

      generator = new FreeTypeFontGenerator(Gdx.files.internal("myfont.ttf"));
      parameter = new FreeTypeFontParameter();


      parameter.size = size;
      dpSize = parameter.size;

      font = generator.generateFont(parameter);
      generator.dispose();

      this.x = x;
      this.y = y;
      this.width = font.getBounds(text).width;
      this.height = font.getBounds(text).height;

   }

   public void render(SpriteBatch sb){

      font.draw(sb, text, x - width / 2   , y + height /2);


   }

   public void renderNoCenter(SpriteBatch sb){

      font.draw(sb, text, x   , y);

   }

   public float getWidth(){
      return this.width;
   }

   public float getHeight(){
      return this.height;
   }

   public void setText(String text){
      this.text = text;
   }

   public void setXY(float x, float y){
      this.x = x;
      this.y = y;
   }

   public void update(float dt){

   }

   public int getDpSize(){
      return dpSize;
   }

   public void dispose(){
      font.dispose();
   }

}

但当我创建这样的新文本时,应用程序会消耗+12mb内存/文本:

Texts play = new Texts("PLAY", 200, 200, 80);
Texts options= new Texts("OPTIONS", 200, 200, 20);

这就是我的问题,谢谢你的帮助


共 (1) 个答案

  1. # 1 楼答案

    生成200像素的字体将用相当大的位图字体字形页面填充视频内存。如果您使用了许多不同的字体类型和/或比例(或者只有一种大比例字体),您可能需要研究如何实现距离字段字体。看看这个答案:How to draw smooth text in libgdx?

    另一个选项是创建图像,并使用Scene2d ImageButton代替可点击文本