Optimized font rendering on SPI LCDs
The open source community has a few large contributors (e.g. Arduino, Google, Adafruit, Microsoft) and their contributions usually set the standard for certain projects and code libraries. I contribute to open source as a way of paying back what I've learned from it. This is not a knock on them to admit that performance is usually not their number one priority, while it usually is mine. Which brings us the reason for this blog post - drawing fonts on inexpensive LCD displays. This has been mostly the exclusive domain of Adafruit's GFX library, but the performance of that code is quite slow, especially on slow MCUs like the Arduino Uno.
Adafruit created a good system of converting TrueType fonts into a simpler bitmap format that makes it easy to draw on low power MCUs. They converted the vector data into an array of small bitmaps with an index to reference the start and size of each bitmap. The performance problem comes from the way characters are drawn on the display. As I demonstrated in a recent blog post, in order to get the best performance out of serial displays, the maximum amount of data needs to be sent in each data transaction. Here's the code which I'm referring to:
The code above loops over the pixels of the character bitmap and draws any foreground pixels (set bits) that it finds. For each foreground pixel, it calls the writePixel() or writeFillRect() functions which test boundaries, set the LCD write window and then finally write the pixel(s). In other words, the loop is mighty slow. Here's a video of it in action on a ATmega328 (Uno equivalent). It's drawing text over the same area with different colors:
The method I use in my imaging library defines the character bounding box as a "memory window" on the LCD one time, then writes the data one scan line at a time (it also skips over empty areas quicker).
The following video shows that the same MCU doing the same operations on the same LCD can run much faster when the code works with (instead of against) the properties of the display. On faster MCUs the difference between the slower code and mine becomes more pronounced. On the ESP32, the more efficient code is 30-50x faster: