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

后端 未结 3 659
無奈伤痛
無奈伤痛 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 09:07

    Updated the answer to libgdx version 1.7.1-SNAPSHOT:

    The easiest way to do this, is to use the TextButton class from libgdx. The text from a TextButton is centered by default. This still works!

    Updated example:

    final BitmapFont font = new BitmapFont();
    
    final String text = "Test";
    
    final GlyphLayout layout = new GlyphLayout(font, text);
    // or for non final texts: layout.setText(font, text);
    
    final float fontX = objectX + (objectWidth - layout.width) / 2;
    final float fontY = objectY + (objectHeight + layout.height) / 2;
    
    font.draw(batch, layout, fontX, fontY);
    

    Outdated example:

    This no longer works!

    If you do not want to use it, you can get the font width and height with:

        font.getBounds("Test text");
    

    So you can do something like this:

        String fontText = "";
        fontX = buttonX + buttonWidth/2 - font.getBounds(fontText).width/2;
        fontY = buttonY + buttonHeight/2 + font.getBounds(fontText).height/2;
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题