【发布时间】:2013-05-12 02:53:18
【问题描述】:
我想知道如何以像素为单位获取字符串的 宽度
【问题讨论】:
我想知道如何以像素为单位获取字符串的 宽度
【问题讨论】:
要测量String 的宽度,请使用Font 并获取String 的bounds,您将要进行绘制。
BitmapFont.getBounds(String str).width
您也可以获得正确偏移的高度以进行绘图。只需将宽度替换为高度即可。
对于多行文本,使用getMultiLineBounds(someString).width 获取边界。
BitmapFont API 在 1.5.7 中发生了变化,因此现在有一种不同的方式来获取边界:
BitmapFont.TextBounds 和 getBounds 完成。相反,将字符串提供给 GlyphLayout 并使用其宽度和高度字段获取边界。然后,您可以通过将相同的 GlyphLayout 传递给 BitmapFont 来绘制文本,这意味着字形不必像以前那样布置两次。
示例:
GlyphLayout layout = new GlyphLayout(); //dont do this every frame! Store it as member
layout.setText("meow");
float width = layout.width;// contains the width of the current set text
float height = layout.height; // contains the height of the current set text
【讨论】:
setText (BitmapFont font, CharSequence str) 方法。
根据@Nates 的回答:https://stackoverflow.com/a/20759876/619673 调用方法
BitmapFont.getBounds(String str).width
并不总是返回正确的宽度!特别是当您重用字体时。
如果你想绘制文本,例如in the center of part of view port,你可以通过其他方法避免这个问题
BitmapFont.drawWrapped(...)
示例代码:
font.drawWrapped(spriteBatch, "text", x_pos, y_pos, your_area_for_text, BitmapFont.HAlignment.CENTER);
【讨论】:
如果您在 UI 中使用皮肤,则很难找到正确的字体以输入 GlyphLayout。
在这种情况下,我使用 Label 的一次性实例为我计算出所有内容,然后向 Label 询问宽度。
Skin skin = getMySkin();
Label cellExample = new Label("888.88888", skin);
cellExample.layout();
float cellWidth = cellExample.getWidth();
Table table = new Table(skin);
table.defaults().width(cellWidth);
// fill table width cells ...
如果您想自己定位文本,这不是答案,但它有助于使 UI 布局稳定并减少对单元格实际内容的依赖。
【讨论】: