I wonder know how to get the width of my string in pixels
3 Answers
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.
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.
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
-
1Which font does this calculate the layout for? – TimSim Jun 23 '16 at 22:04
-
5You can specify that yourself. Use the method `setText (BitmapFont font, CharSequence str)` on GlyphLayout. – Tobiaswk Jul 03 '16 at 14:50
-
7@BennX i used glyphLayout.setText(BitmapFont font, CharSequence str). i could not find glyphLayout.setText(CharSequence str) – Iftikar Urrhman Khan Apr 17 '17 at 11:09
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);
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.

- 1,076
- 9
- 9