Search code examples
libgdxtext-rendering

Draw multi-line BitmapFont vertically centered


I wish to center some long wrapped text that spans several lines on a rectangle (or anything else) like in the image below (I don't need to hide excess text but it'd be a big plus I'd be so grateful):

enter image description here

I've been able to achieve vertical centering with a single-line text like below:

BitmapFont font = new BitmapFont();
String text = "Hello";
Rectangle bounds = new Rectangle(0, 0, 100, 100);

void render(SpriteBatch spriteBatch) {
    font.draw(
        spriteBatch,
        text,
        bounds.x,
        bounds.y + bounds.height / 2f + font.getLineHeight());
}

I know there's a BitmapFont.draw() method variant that lets you specify horizontal alignment, the target width of your text and a wrapping flag but I can't seem to find a way to vertically align multi-line text.

In the past this was possible with BitmapFont.getBounds() and some math but there's no such method in LibGDX 1.9.9.


Solution

  • Using the GlyphLayout class we can get the height of your wrapped text, I've made a helper method to center the text inside a Rectangle improving the readability of code in the main render() method of our apps/games:

    private static GlyphLayout glyphLayout = new GlyphLayout();
    public static void drawCentered(BitmapFont font, SpriteBatch spriteBatch,
                                        String text, Rectangle bounds) {
            glyphLayout.setText(font, text, Color.BLACK, bounds.width, Align.center, true);
            font.draw(
                    spriteBatch,
                    text,
                    bounds.x,
                    bounds.y + bounds.height / 2f + glyphLayout.height / 2f,
                    bounds.width,
                    Align.center,
                    true);
        }