How get a string width in Libgdx?

时光毁灭记忆、已成空白 提交于 2019-11-26 16:07:35

问题


I wonder know how to get the width of my string in pixels


回答1:


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.

In addition for multiline texts use getMultiLineBounds(someString).width to get the bounds.


BitmapFont API >= 1.5.6

The BitmapFont API changed in 1.5.7 so there is a different way to get the bounds now:

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.

Source

Example:

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



回答2:


According to @Nates answer: https://stackoverflow.com/a/20759876/619673 calling method

BitmapFont.getBounds(String str).width

not always returns proper width! Especially when you are reusing font. If you want draw text for example in the center of part of view port, you can avoid this problem by using another method

BitmapFont.drawWrapped(...)

Example code:

 font.drawWrapped(spriteBatch, "text", x_pos, y_pos, your_area_for_text, BitmapFont.HAlignment.CENTER);



回答3:


If you use skins in UI it is a hassle to find out the correct font to feed into the GlyphLayout.

In this case I use a throw away instance of Label to figure everything out for me then ask the Label for the width.

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 ...

This is not the answer if you want to position the text yourself, but it is useful to make a UI layout stable and less dependent on the actual content of the cells.



来源:https://stackoverflow.com/questions/16600547/how-get-a-string-width-in-libgdx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!