Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

How get a string width in Libgdx?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...