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

混江龙づ霸主 提交于 2019-12-01 15:45:43

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;

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);
Anindya Sankar Dasgupta

Try the following:

label.setPosition(Gdx.graphics.getWidth()/2-(label.getPrefWidth()/2),Gdx.graphics.getHeight()-(label.getPrefHeight()/2));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!