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

LeS*_*Sam 23 width libgdx

我想知道如何获得我的字符串的宽度(以像素为单位)

Ben*_*nnX 64

BitmapFont API <1.5.6

为了MESURE的宽度String您使用Font并得到boundsString,你要画.

BitmapFont.getBounds(String str).width
Run Code Online (Sandbox Code Playgroud)

BitmapFont API

您也可以获得正确偏移的高度以进行绘制.只需用高度替换宽度.

此外,多线文本用于getMultiLineBounds(someString).width获取界限.


BitmapFont API> = 1.5.6

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
Run Code Online (Sandbox Code Playgroud)

  • @BennX我使用了glyphLayout.setText(BitmapFont字体,CharSequence str).我找不到glyphLayout.setText(CharSequence str) (5认同)
  • 你可以自己指定.在GlyphLayout上使用`setText(BitmapFont font,CharSequence str)`方法. (3认同)

dea*_*ish 5

根据@Nates的回答:https://stackoverflow.com/a/20759876/619673 调用方法

BitmapFont.getBounds(String str).width
Run Code Online (Sandbox Code Playgroud)

并不总是返回适当的宽度!特别是当您重复使用字体时.例如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);
Run Code Online (Sandbox Code Playgroud)