问题描述
我想知道如何以像素为单位获取字符串的 宽度
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 并使用其宽度和高度字段获取边界.然后,您可以通过将相同的 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
这篇关于如何在 Libgdx 中获取字符串宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!