Libgdx: Is there an easy way to center text on each axis on a button?

后端 未结 3 655
無奈伤痛
無奈伤痛 2021-01-17 08:43

I have been trying to figure out a way to center text on a button, but can\'t find an easy, multi-purpose way to. I can do it, but it will only work for a certain string, no

3条回答
  •  隐瞒了意图╮
    2021-01-17 08:48

    For the newer version of libgdx the function BitMapFont.getBounds() isn't there in api anymore. You can use GlyphLayout to get bounds.For example,

    BitmapFont font;
    SpriteBatch spriteBatch;
    //... Load any font of your choice first
    FreeTypeFontGenerator fontGenerator = new FreeTypeFontGenerator(
       Gdx.files.internal("myFont.ttf")
    );
    FreeTypeFontGenerator.FreeTypeFontParameter freeTypeFontParameter =
          new FreeTypeFontGenerator.FreeTypeFontParameter();
    freeTypeFontParameter.size = size;
    fontGenerator.generateData(freeTypeFontParameter);
    font = fontGenerator.generateFont(freeTypeFontParameter);
    
    //Initialize the spriteBatch as requirement
    
    GlyphLayout glyphLayout = new GlyphLayout();
    String item = "Example";
    glyphLayout.setText(font,item);
    float w = glyphLayout.width;
    font.draw(spriteBatch, glyphLayout, (Game.SCREEN_WIDTH - w)/2, y);
    

提交回复
热议问题