Wednesday, January 30, 2013

Kerning, Wrapping and Text Alignment

In my current project, I'm using the FTGL library for text rendering which does the job reasonably well, for Android I'm using a FTGL port called FTGLES (Ideally at some point I'd just like to be using just one of these.)

FTGL is very simple to get working but it doesn't support text alignment and text wrapping to the extent that I'd like. Therefore I've spent sometime modifying it a little and rewriting the central render loop (making it a little more efficient as a nice bonus too). Here's how everything looks now it's finished:

Horizontal Alignment

I want to be able to align my text to the left, right or center on the horizontal like so:

By default FTGL doesn't have support for right alignment. But it's pretty easy - just a case of getting the pixel width of the text and subtracting it from the x position. It's a little harder when text wrapping is involved.

Vertical Alignment

I want to be able to align my text top, bottom, center on the horizontal like so:

This is a little trickier because to do this well, you need to know where the baseline is (say if your were writing on lined paper, then the baseline would be one of those lines.) This wasn't easy to get out of FTGL so I worked around it.

The code supports any combination of horizontal and vertical alignments.

Consistent Baseline

If I render three pieces of text at the same Y position, I'd like it to appear as if each piece of text falls on the same baseline. Like so:

Text Wrapping

I want to be able to wrap paragraphs of text according to a maximum width. This text wrapping also needs to support the above alignment code. This picture uses a different font.

This shows only 3 of the possible wrapping alignment permutations but they're all supported. The text can also be scaled arbitrarily and everything still works fine.

I'm happy to stop working on this now. Though there are other features I could add: markup for colouring specific words in a text string, making FTGL go through my engine's pipeline like everything else, justified alignment, I suspect I've probably broken unicode support so testing that and fixing it would be good!

The hacked up code is available here:


Unknown said...

Hello! Would you consider releasing your modifications to FTGL? I find myself needing to implement something similar in a project already using FTGL.


balaam said...

Yes, I should do that - but fair warning, this wasn't a clean update, I made a some minor changes to FTGL and then create a new .h .cpp to handle all alignment I wanted :D

I'll see if I can get something up on GitHub this weekend. I'll probably just upload the files that I changed and alignment files I added.

balaam said...

Hey Stephen,

I've put the code changes up here:

Don't know how helpful they'll be, but hope you can some use out it!