Tuesday, October 9, 2012

Android font metrics for dummies

Recently I was working on a custom View with overridden onDraw method and at some point I needed to center some text vertically. Unfortunately Paint.setTextAlign() supports only horizontal orientation, so I tried calculating the y-coordinate of the origin myself, but I couldn't get it exactly right. After two failed attempts I decided that I need a program which visualizes the available font metrics, because it seems that I do not understand the FontMetrics documentation, or the aforementioned class and it's documentation sucks.

You can find the source code on my GitHub, and here's the screenshot for other typographically challenged programmers:



(BTW: the word "Żyłę" used there is not a complete gibberish, it's an accusative case of word "vein" in Polish; it's nice, because it's short, but it covers all cases of the metrics class).

Let's get back to vertical alignment. In general you should center text vertically either on x-height or on half the cap height above the baseline (at least that's the info I found). Neither metric is directly available in FontMetrics class, but you can approximate the cap height as a (textSize - descent) or calculate x-height yourself using Rect height returned by Paint.getTextBounds for string "x".