Search code examples
javaandroidfontslibgdxfreetype

Custom, clickable font


I'm tryin to make a custom, clickable font to my game (for the menu, like: PLAY -> goes to playscreen), I've tryied with FreeType but when i make a new text with it, it uses a lot of memory on android. Can you suggest me a proper way to create a clickable texts from .ttf files? I did in this way:

I have a Box class:

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;
   } 
}

Then the Texts class and its extends the box, so when i create a new Text, i can call .contains(x,y) so i can make the text clickable:

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();
   }

}

But when i create a new texts like this, the app consume + 12mb RAM / Texts:

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

So thats my, problem, thanks for the help!


Solution

  • Generating fonts at 200 pixels will fill up your video memory with rather big pages of bitmap font glyphs. If you use lots of different font types and/or scales (or just one big scaled font) you might want to look into implementing distance field fonts. Look at this answer: How to draw smooth text in libgdx?

    Another option would be to create images and use Scene2d ImageButton in stead of clickable text.