Convert TrueType to Bitmap Fonts for C++

It was easy to add the OLED display to a Particle Photon but there was only one font and it was very small and ugly. Making good fonts takes some work.

Note (12/23/2017): I found an elusive bug in the part of the original code that displayed it on an OLED and have updated the published code here with the repairs.

If you search on the web for bitmap fonts you don’t find much that’s large (taller than 12 pixels) and good. So, it turns out that the best approach is to create them from TrueType fonts.

Generate the bitmap font

I used Bitmap Font Generator to generate the fonts. This program creates an image with a preferred subset of the characters displayed. It also creates a metadata file that describes each character in the image (height, width, offset,…).

Here are the two dialogs I used. Most important is to ensure the width of the output bitmap is large enough for the entire font set to display in a single line. Also ensure the bit depth is 8 and the height is fixed.

Bitmap Font Generator Settings

Note that I used a subset of the character set (don’t need them all). By default I use a fnt suffix for the metadata file (the Save bitmap as… file name).

Convert the PNG and FNT to C++ Structures

Once the image is created it has to be converted from a PNG to C++ code. I wrote two functions in Python to convert the image data into something that is C++ compatible.

These are followed by the supporting C++ code to show how to use the data structures. First are sample Arial11 files and then the actually Font display code used by the Photon when displaying on an OLED display.

The first function takes an 8 bit PNG file (as produced by BFG) and crops it then writes out the bits as hex data ready to go into a C++ file. The second function writes out the metadata as a list of structures again ready to go into a C++ file.

Finally, there’s a small amount of C++ code to read the data and use it to display the text. Take a look at the entire GIST for the rest of the code.