Libgdx: Is there an easy way to center text on each axis on a button?(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:有没有一种简单的方法可以使按钮上每个轴上的文本居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Libgdx:有没有一种简单的方法可以使按钮上每个轴
基础教程推荐
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
