Bitmap fonts in XNA

Originally posted to Shawn Hargreaves Blog on MSDN, Thursday, April 26, 2007

The XNA font system is most commonly used to extract data from TrueType fonts described in XML files, but it is also capable of grabbing character images directly from hand drawn bitmaps.

TrueType fonts are convenient, but you may sometimes find yourself wanting a more distinctive look for your text. You can create custom typefaces by arranging a set of character images into a single bitmap, separating the areas between each letter with a pure magenta marker color:

This bitmap must include an alpha channel to specify which areas should be solid or transparent, and the alpha in the magenta border region must be set to fully opaque.

When you add this file to your Game Studio Express project, it will default to the "Texture" content importer and "Texture (Sprite, 32bpp)" content processor. To indicate that this is a special bitmap which should be converted into a font, you need to change the processor to "Font Texture":

Fonts that were created from bitmaps can be loaded and displayed by the SpriteFont class in exactly the same way as ones converted from XML description files. Using the embossed bitmap font shown above, I can render funky embossed writing:

At this point you may be worrying that drawing an entire font into a bitmap by hand is not your idea of fun. And you'd be right. I wouldn't enjoy it much either.

Fortunately, the kindly little gremlins who work at XNA CGP GSE Samples & Utilities, Inc, saw this problem coming and wrote a program to take care of it. This presents a user interface for selecting what TrueType font you want to use as a starting point:

When you click the Export button it does basically the same thing as the regular XML font description processor, but outputs the character images into a bitmap file separated by magenta marker regions.

I created my embossed font by running the ttf2bmp utility, taking the resulting bitmap into Photoshop, selecting everything except the magenta areas, running an emboss filter over it, and then feeding this modified image into the content pipeline "Font Texture" processor.

Blog index   -   Back to my homepage