Libgdx:是否有一种简单的方法可以将按钮上每个轴的文本居中? [英] Libgdx: Is there an easy way to center text on each axis on a button?

查看:204
本文介绍了Libgdx:是否有一种简单的方法可以将按钮上每个轴的文本居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图找到一种方法来将文本置于按钮上,但找不到一种简单,多用途的方法。我可以做到,但它只适用于某个字符串,而不适用于任何字符串。我想知道是否有办法将任何字符串置于按钮上。在这种情况下我的按钮是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:是否有一种简单的方法可以将按钮上每个轴的文本居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆