A Trick to Render Outlined Text
Sunday, February 11th, 2007In the last few years I found myself in need to render a font outlined to increase readability or to comply with UI requirements.
In both cases I had a non-outlined font, I had no choice of picking a different one, and I had to render it outlined.
To give you example, I had to render a font like this:

Outlined, like this:

If you are not too concerned about rendering speed (in my case, it wasn’t an issue), the trick I used to accomplish this is astonishingly simple, and very effective. You just need to render the font 5 times in different positions; 4 times with the color of the outline, and one time with the color of the body of the text.
Assuming that you want the body of the text starting at position (x,y) on the screen, the algorithm is:
A) Select the outline color.
1) Draw the text at (x+1,y)
2) Draw the text at (x-1,y)
3) Draw the text at (x,y+1)
4) Draw the text at (x,y-1)
B) Select the font body color
5) Draw the text at (x,y)
Here is an example of the results you get after each draw, numbered as in the above steps. In the example the color of the outline is BLACK, and the color of the body of the text is RED. I also added a background with a color similar to color of the body of the text, to show how outlining can increase readability in cases where you don’t know what the color of the background is (like in cases where the background could be any image).

To make it even clearer for you I did the same thing but this time I rendered the body of the text in gray after each steps 1,2,3 and 4. This way it becomes very clear how the outline is constructed, with each draw, around the body of the text:

In Java, a very simple example of a method that does exactly what described looks like:
public void drawTextOutlined(Graphics g, String text, int x, int y, Color cOutline, Color cBody) { g.setColor(cOutline); g.drawString(text, x+1, y); g.drawString(text, x-1, y); g.drawString(text, x, y+1); g.drawString(text, x, y-1); g.setColor(cBody); g.drawString(text, x, y); }
Variations:
This method of outlining can be used with pretty much anything that you can render in a given color; it doesn’t have to be only text. In some cases it can even be expanded to images. It’s somewhat of a long story, but if anybody cares I can post about that as well.
There are also many variations based on the same concept. For example you can draw the outline rendering the text in the outline color at positions (x+1,y+1) (x+1,y-1) (x-1,y+1) (x-1,y-1) with similar results. You can also try drawing the outline with only two renderings of the text in the outline color, at positions (x+1,y+1) (x-1,y-1) or (x-1,y-1) (x+1,y+1), saving two text renderings and obtaining OK results in most cases.
I prefer the variations presented here, which gave me the best results in the situations I had, but feel free to experiment. There are cases where different variations might give you better results.
Hope you’ll find this helpful.