簡體   English   中英

Libgdx:有沒有一種簡單的方法可以讓按鈕的每個軸上的文本居中?

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

我一直試圖找出一種將文本居中放在按鈕上的方法,但找不到一種簡單的、多用途的方法。 我可以做到,但它只適用於某個字符串,不適用於任何字符串。 我想知道是否有辦法將任何字符串放在按鈕上。 在這種情況下,我的按鈕是 185x50。

我已經能夠將此按鈕置於屏幕中央,如下所示:

buttonX = WIDTH / 2 - (screen.getRegionWidth() / 2);
buttonY = HEIGHT / 2 - (screen.getRegionHeight() / 2);

任何幫助將非常感激。 :)

更新了 libgdx 版本 1.7.1-SNAPSHOT 的答案:

最簡單的方法是使用 libgdx 中的 TextButton 類。 TextButton 中的文本默認居中。 這仍然有效!

更新示例:

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

過時的例子:

這不再有效!

如果您不想使用它,您可以通過以下方式獲取字體寬度和高度:

    font.getBounds("Test text");

所以你可以做這樣的事情:

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

對於較新版本的 libgdx,函數 BitMapFont.getBounds() 不再存在於 api 中。 您可以使用 GlyphLayout 來獲取邊界。例如,

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

請嘗試以下操作:

label.setPosition(Gdx.graphics.getWidth()/2-(label.getPrefWidth()/2),Gdx.graphics.getHeight()-(label.getPrefHeight()/2));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM