且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Libgdx 中获取字符串宽度?

更新时间:2023-01-06 12:17:39

BitmapFont API <1.5.6

要测量 String 的宽度,请使用 Font 并获取 Stringbounds,你要画画了.

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

BitmapFont API

您也可以获得正确偏移的高度以进行绘图.只需将宽度替换为高度即可.

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 来绘制文本,这意味着字形不必像以前那样布置两次.

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