How get a string width in Libgdx?

Solution 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 (Web archive)

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

Solution 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);