How get a string width in Libgdx?

后端 未结 3 788
一整个雨季
一整个雨季 2020-12-01 09:06

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

3条回答
  •  臣服心动
    2020-12-01 09:53

    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
    

提交回复
热议问题