如何在Libgdx中获得字符串宽度? [英] How get a string width in Libgdx?
问题描述
我想知道如何获得我的字符串的宽度(以像素为单位)
I wonder know how to get the width of my string in pixels
推荐答案
BitmapFont API< 1.5.6
要确保String
的宽度,请使用Font
并获取String
的bounds
,您将要绘制.
BitmapFont API < 1.5.6
To mesure the width of a String
you use your Font
and get the bounds
of the String
, you are going to draw.
BitmapFont.getBounds(String str).width
您也可以为正确的偏移量将高度设置为.只需将宽度替换为高度即可.
You can get the height to for the right offset for drawing too. Just replace width with height.
此外,对于多行文字,请使用getMultiLineBounds(someString).width
来获取边界.
In addition for multiline texts use getMultiLineBounds(someString).width
to get the bounds.
BitmapFont API在1.5.7中进行了更改,因此现在有另一种获取边界的方法:
The BitmapFont API changed in 1.5.7 so there is a different way to get the bounds now:
BitmapFont.TextBounds和getBounds完成.相反,将字符串提供给GlyphLayout并使用其width和height字段获取界限.然后,您可以通过将相同的GlyphLayout传递给BitmapFont来绘制文本,这意味着这些字形不必像以前那样进行两次布局.
BitmapFont.TextBounds and getBounds are done. Instead, give the string to GlyphLayout and get the bounds using its width and height fields. You can then draw the text by passing the same GlyphLayout to BitmapFont, which means the glyphs don’t have to be laid out twice like they used to.
示例:
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
这篇关于如何在Libgdx中获得字符串宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!