Text layout with GlyphLayout and ScreenViewport in libGDX

I want to post some code (and screenshots!) for laying out text on screen with libGDX. libGDX changed the way it handles text recently, so I wanted to write new code to accommodate, and I also wanted to make the layout work relative to the bounds of a Viewport. GUI code can get to be a hassle real fast, so to keep it simple, there’s just three options for horizontal layout (left, center, right), and three for vertical layout (bottom, middle, top). Here’s the code:

Code

UILabel holds layout and rendering.

The function layout() does the actual math. It gets called after screen resize and during UILabel creation. I know there’s some unnecessary math in there, but this is for clarity, not optimizing every FLOP. Besides, we’re in Java.

And this is how they get drawn:

Pictures

When debugging position calculations for various viewports, I used ShapeRenderer to draw concentric circles drawn around the text in case the text rendered off screen, as it often did. I also drew straight lines from the origin to UILabel position. I liked the look, so here’s some screenshots from the debug process.

Top-aligned text. Camera over (0, 0).

Top-aligned text. Camera over (0, 0).


Middle-aligned text.

Middle-aligned text.


Bottom-aligned text.

Bottom-aligned text.


All layout test text.

All layout test text.


Top-aligned text. Camera centered over world.

Top-aligned text. Camera centered over world.


Bottom-aligned text.

Bottom-aligned text.


All test text with camera centered over the world.

All test text with camera centered over the world.

Leave a Reply

Your email address will not be published. Required fields are marked *