我一直在想办法让按钮上的文本居中,但找不到一种简单、多用途的方法.我可以做到,但它只适用于某个字符串,不适用于任何字符串.我想知道是否有办法让按钮上的任何字符串居中.在这种情况下,我的按钮是 185x50.
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, not for any string. i would like to know if there is a way to center any string on a button. My button in this case is 185x50.
我已经能够使这个按钮在屏幕上居中,如下所示:
I have been able to center this button on the screen, like so:
buttonX = WIDTH / 2 - (screen.getRegionWidth() / 2);
buttonY = HEIGHT / 2 - (screen.getRegionHeight() / 2);
任何帮助将不胜感激.:)
Any help would be much appreciated. :)
更新了libgdx版本1.7.1-SNAPSHOT的答案:
Updated the answer to libgdx version 1.7.1-SNAPSHOT:
最简单的方法是使用 libgdx 中的 TextButton 类.TextButton 中的文本默认居中.这仍然有效!
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!
更新示例:
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);
过时的例子:
这不再有效!
如果不想使用,可以通过以下方式获取字体宽度和高度:
If you do not want to use it, you can get the font width and height with:
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:有没有一种简单的方法可以使按钮上每个轴上的文本居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!