pixelfont: bitmap font renderer for ESP-IDF

A display wants pixels, a font is a picture of characters. The library turns a font into data and draws it into whatever the display calls a frame, so the same code draws any font, at any size and scale.

Features

  • Text in UTF-8 with scaling, letter spacing, transparency and inverse video.

  • Bitmaps of any size, scaled the same way, so icons live next to the text.

  • Three block formats and the page format of the SSD1306 GDDRAM, whose buffer the library can write into directly.

  • Two ways to draw: into a buffer, or straight to a callback, block by block.

  • Fonts as data: bundled Terminus, any BDF or PSF file through tools/pixelfont.py, and the same files loadable at runtime.

Bundled fonts

Font

Cell

Coverage

Terminus Medium 8x16

8x16

Latin: U+0020..U+007E, U+00A0..U+00FF

Terminus Medium 12x24

12x24

Latin: U+0020..U+007E, U+00A0..U+00FF

CONFIG_PIXELFONT_FONTS lists the fonts to compile in, CONFIG_PIXELFONT_DEFAULT_FONT picks the one available as PIXELFONT_FONT_DEFAULT. The fonts are under the SIL Open Font License, see LICENSE-OFL; the library is under the MIT license.

Other scripts are a generation away: tools/pixelfont.py cuts a font by code point ranges or by the characters of a text, so Cyrillic, Greek or box drawing cost only what they use. See fonts/README.md.

What a font costs in the image

A bundled font takes its glyph index and its bitmaps in the firmware only if the application uses it. The files listed in CONFIG_PIXELFONT_FONTS are compiled into the library, but the linker does not pull an object out of a library when nothing refers to it, and --gc-sections drops the data that is linked but never reached. A font that is only selected in the menuconfig, therefore, does not cost a byte of the flash image; nm build/*.elf | grep pixelfont_font shows what really got in.

The digits example relies on that: it draws with a font loaded from the file system and never mentions PIXELFONT_FONT_DEFAULT, so its image contains no built-in font at all, and the only font data on the flash is the BDF file in the file system image. To make this explicit, or to save the build time of the font files, set CONFIG_PIXELFONT_FONTS to an empty string: then no font is compiled, and fonts/pixelfont_fonts.h deliberately fails to compile if something still includes it.

Two ways to draw

A canvas either has a buffer or a callback. With a buffer the pixels are written in place, so a text can be drawn over a picture; without an opaque style only the set pixels of the glyphs touch the buffer. Without a buffer the renderer composes the drawing in blocks and passes each of them to the callback, which is the only way with a display that cannot be read back and has no RAM for a frame.

static uint8_t framebuffer[128 * 64 / 8];

pixelfont_canvas_t canvas = {
    .width = 128,
    .height = 64,
    .pack = PIXELFONT_PACK_PAGE,
    .data = framebuffer,
    .size = sizeof(framebuffer),
};

pixelfont_style_t style = PIXELFONT_STYLE_DEFAULT;
style.scale = 2;

esp_err_t err = pixelfont_draw_text(PIXELFONT_FONT_DEFAULT, &canvas, 8, 4, "Hello", &style);
// ... and let the driver send the buffer: ssd1306_flush(&display)

Boxed canvases come from pixelfont_canvas_new() and go away with pixelfont_canvas_free().

Clipping

Everything is clipped to the surface: a glyph, a bitmap or a rectangle that leaves the edge is drawn up to the edge and cut there, so a long string can run off the screen instead of being dropped as a whole or wrapped. Coordinates may be negative, which is handy to scroll a line out of view.

Inverse video

A style with opaque and reversed draws the cells filled and the glyphs as holes in them, so white text on a black panel becomes black text on white, which is what a highlighted menu item or a selected line looks like. pixelfont_draw_bitmap() takes the same flag, and pixelfont_invert() turns a whole buffered canvas inside out, which is the same as a panel with inverted colours.

Formats

The packing of a buffer and of the blocks in the callback is one of

Packing

Byte order

Bit of the first pixel

PIXELFONT_PACK_ROW

rows left to right, bytes across

7

PIXELFONT_PACK_PAGE

pages of eight rows, bytes down a column

0 (SSD1306 GDDRAM)

PIXELFONT_PACK_COLUMN_MSB

columns top to bottom, bytes down a column

7

PIXELFONT_PACK_COLUMN_LSB

columns top to bottom, bytes down a column

0

Drawing

pixelfont_draw_text() walks the string byte by byte, decodes UTF-8 and replaces a character the font does not have with ?, or U+FFFD, or skips it when the font has neither. pixelfont_draw_glyph() draws one code point, pixelfont_find_glyph() looks one up, pixelfont_draw_bitmap() draws a 1 bit per pixel image and pixelfont_fill_rect() fills a rectangle. Everything is clipped against the canvas, so a text may start outside of it.

pixelfont_set_clip() narrows the drawing to a rectangle and pixelfont_reset_clip() removes it. The rectangle is intersected with the surface, everything drawn after that stops at its edges, and the pixels outside of it are not touched, so a text area can be kept apart from the rest of the picture:

pixelfont_set_clip(&canvas, 0, 16, 128, 48);

pixelfont_fill_rect(&canvas, 0, 16, 128, 48, false);  // only the area
pixelfont_draw_text(font, &canvas, 4, 16, "line 1", NULL);

pixelfont_reset_clip(&canvas);

The flush callback and pixelfont_invert() work on the whole canvas.

Scrolling

A text area scrolls smoothly when its lines are drawn again on every frame one pixel higher, with the clip rectangle cutting what has left the area and what has not entered it yet:

pixelfont_set_clip(&canvas, 0, 16, 128, 48);

for (int step = 0; step < 3 * 16; step++)
{
    int offset = step % 16, first = step / 16;

    pixelfont_fill_rect(&canvas, 0, 16, 128, 48, false);   // the area only

    // one line more than fits: the extra one enters through the bottom edge
    for (int row = 0; row <= 3; row++)
    {
        char text[16];
        snprintf(text, sizeof(text), "Line %d", first + row + 1);
        pixelfont_draw_text(font, &canvas, 4, 16 + row * 16 - offset, text, NULL);
    }

    pixelfont_flush(&canvas);
    vTaskDelay(pdMS_TO_TICKS(25));
}

pixelfont_reset_clip(&canvas);

pixelfont_scroll_up() and pixelfont_scroll_down() move the pixels of a rectangle by any number of pixels instead, without redrawing the content, which suits a picture. The rows that leave the rectangle are lost, the rows that become free are the background, and the rest of the canvas does not change. Scrolling needs the canvas buffer, so a canvas that sends the picture to a driver block by block cannot be scrolled — give the canvas a buffer and send it with pixelfont_flush().

pixelfont_text_width() and pixelfont_text_height() measure a string, so a layout does not have to count characters. Like the functions that draw, they return an error code and write the result through a pointer, and everything a caller passes in is checked for validity.

Fonts at runtime

pixelfont_load() reads a BDF or PSF file from a file system of ESP-IDF and builds a font in memory, pixelfont_free() releases it. The loader takes BDF, PSF1 and PSF2; compressed files are not unpacked, so mount the file system as is or convert the font at build time.

Display drivers

The library produces one bit per pixel, so the driver of the display turns that into what the panel wants. Two integrations live in examples/: the SSD1306 panel driver of ESP-IDF, whose page-major memory is exactly PIXELFONT_PACK_PAGE, so the picture travels to the panel without a conversion, and the colour expansion of a one-bit block into 16-bit lines for esp_lcd_ili9341. The other esp_lcd panel drivers take the same code. examples/digits shows the other half of the picture: the font is not a part of the application, tools/pixelfont.py cuts the digits of Terminus 16x32 into a BDF, the file goes into the file system image of the flash, and the application loads it with pixelfont_load() when the screen needs it.

Examples

Four examples, all built with ESP-IDF the same way:

  • examples/default needs no hardware: it draws a frame on a surface that imitates the GDDRAM of a SSD1306 and prints the frame as text. The frame shows text, a bitmap, inverse video, clipping at the edges and a pixel-by-pixel scroll of a text inside a clipped rectangle.

  • examples/ssd1306 drives a real 128x64 OLED through the SSD1306 panel driver of ESP-IDF, esp_lcd_new_panel_ssd1306(). The canvas works right in the page-major buffer of the panel, so a page goes to the display as it is, and the text inside the clipped area scrolls smoothly.

  • examples/ili9341 drives a colour SPI panel through espressif/esp_lcd_ili9341. The 1-bit canvas is expanded to RGB565 line by line, which is all a monochrome renderer needs on a colour display; the frame shows scaling, colour changes and inverse video.

  • examples/digits keeps the font out of the firmware: a BDF file in the SPIFFS partition is loaded with pixelfont_load(). Four Spleen 32x64 digits fill the screen, and a digit that changes rolls in and out like the wheel of a mechanical counter.

cd examples/ssd1306
idf.py set-target esp32
idf.py menuconfig     # Example configuration: the I2C pins and the address
idf.py build
idf.py -p /dev/ttyUSB0 flash monitor

The pins and the address of the display are in menuconfig, and every example has a README with the details of its wiring.

API reference

Defines

PIXELFONT_STYLE_DEFAULT

Default style: scale 1, no spacing, transparent background.

Typedefs

typedef esp_err_t (*pixelfont_flush_t)(void *ctx, int x, int y, int w, int h, const uint8_t *bits)

Write a block of pixels to the display.

Called by the renderer with a block already clipped against the canvas and composed in the packing of the canvas. Every bit of the block is defined: a set bit is a foreground pixel, a clear bit is a background pixel, so the driver may write the block as is without clearing the window first.

Param ctx:

Context of the canvas

Param x:

Left edge of the block, in pixels

Param y:

Top edge of the block, in pixels

Param w:

Width of the block, in pixels

Param h:

Height of the block, in pixels

Param bits:

The pixels: ((w + 7) / 8) * h bytes for PIXELFONT_PACK_ROW, ((h + 7) / 8) * w bytes for the column packings

Return:

ESP_OK on success, an error code of the bus otherwise

Enums

enum pixelfont_pack_t

Layout of the bitmap handed to the flush callback.

The renderer composes a block of pixels in a small buffer and passes it to the driver through pixelfont_flush_t. The layout of that buffer depends on the display: a controller that takes bytes over SPI wants them row by row, a SSD1306 wants a byte per column with the topmost pixel in the lowest bit.

Values:

enumerator PIXELFONT_PACK_ROW

Row-major, bit 7 is the leftmost pixel.

enumerator PIXELFONT_PACK_PAGE

Page-major, bit 0 is the topmost pixel (SSD1306 GDDRAM)

enumerator PIXELFONT_PACK_COLUMN_MSB

Column-major, bit 7 is the topmost pixel.

enumerator PIXELFONT_PACK_COLUMN_LSB

Column-major, bit 0 is the topmost pixel.

Functions

esp_err_t pixelfont_canvas_size(int width, int height, pixelfont_pack_t pack, size_t *size)

Size of a canvas buffer, bytes.

Useful to share a buffer with a display driver that allocates it itself.

Parameters:
  • width – [in] Width, pixels

  • height – [in] Height, pixels

  • pack – [in] Packing of the buffer

  • size – [out] Size in bytes

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument

esp_err_t pixelfont_canvas_new(int width, int height, pixelfont_pack_t pack, pixelfont_canvas_t **canvas)

Allocate a canvas with a buffer.

The buffer is cleared to the background.

Parameters:
  • width – Width, pixels

  • height – Height, pixels

  • pack – Packing of the buffer

  • canvas – [out] The canvas

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument, ESP_ERR_NO_MEM if there is not enough memory

void pixelfont_canvas_free(pixelfont_canvas_t *canvas)

Free a canvas allocated with pixelfont_canvas_new()

Parameters:

canvas – Canvas, NULL is allowed

esp_err_t pixelfont_set_clip(pixelfont_canvas_t *canvas, int x, int y, int width, int height)

Limit the drawing to a rectangle.

Everything the renderer draws afterwards is cut at the edges of the rectangle: the text that leaves it is clipped, the pixels outside it are not touched. The rectangle is intersected with the canvas, so a text drawn partly or completely outside of it draws nothing there. This is what makes a line of a terminal enter from below the text area and leave above it a pixel at a time, when the text is drawn at a moving offset.

pixelfont_fill_rect() and pixelfont_scroll_up() obey the rectangle too, so a rectangle may be cleared without touching the rest of the picture. pixelfont_flush() and pixelfont_invert() work on the whole canvas.

Parameters:
  • canvas – Canvas

  • x – Left edge, pixels

  • y – Top edge, pixels

  • width – Width, pixels, must be positive

  • height – Height, pixels, must be positive

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument

esp_err_t pixelfont_reset_clip(pixelfont_canvas_t *canvas)

Remove the rectangle set by pixelfont_set_clip()

Parameters:

canvas – Canvas

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument

esp_err_t pixelfont_invert(const pixelfont_canvas_t *canvas)

Invert the pixels of a canvas.

Turns the set pixels clear and the clear pixels set, the same result as a display with an inverted panel. Works on a canvas with a buffer only.

Parameters:

canvas – Canvas with a buffer

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument, ESP_ERR_INVALID_STATE when the canvas has no buffer

esp_err_t pixelfont_flush(const pixelfont_canvas_t *canvas)

Send the buffer of a canvas to the display.

Calls pixelfont_flush_t for horizontal strips of up to eight rows, which is one page of a SSD1306. Does nothing when the canvas has no callback.

Parameters:

canvas – Canvas with a buffer

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument, an error code of the driver otherwise

esp_err_t pixelfont_draw_text(const pixelfont_t *font, const pixelfont_canvas_t *canvas, int x, int y, const char *text, const pixelfont_style_t *style)

Draw a UTF-8 string.

The glyphs are drawn left to right starting at (x, y), which is the top left corner of the first cell. Code points that the font does not have are substituted: ‘?’ when the font has it, U+FFFD otherwise, and skipped if the font has neither.

Without an opaque style only the set pixels of the glyphs touch the canvas, so a text can be drawn over a picture.

Parameters:
  • font – Font

  • canvas – Drawing surface

  • x – Left edge of the first cell, pixels

  • y – Top edge of the cells, pixels

  • text – NUL-terminated UTF-8 string

  • style – Drawing style, NULL for PIXELFONT_STYLE_DEFAULT

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument, an error code of the driver otherwise

esp_err_t pixelfont_draw_glyph(const pixelfont_t *font, const pixelfont_canvas_t *canvas, int x, int y, uint32_t codepoint, const pixelfont_style_t *style)

Draw one code point.

Parameters:
  • font – Font

  • canvas – Drawing surface

  • x – Left edge of the cell, pixels

  • y – Top edge of the cell, pixels

  • codepoint – Unicode code point

  • style – Drawing style, NULL for PIXELFONT_STYLE_DEFAULT

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument, ESP_ERR_NOT_FOUND if the font has no such glyph, an error code of the driver otherwise

esp_err_t pixelfont_draw_bitmap(const pixelfont_canvas_t *canvas, int x, int y, int width, int height, const uint8_t *bits, uint8_t scale, bool opaque, bool reversed)

Draw a one-bit bitmap.

The bitmap is row-major, the most significant bit is the leftmost pixel, every row occupies (width + 7) / 8 bytes.

Parameters:
  • canvas – Drawing surface

  • x – Left edge, pixels

  • y – Top edge, pixels

  • width – Width of the bitmap, pixels

  • height – Height of the bitmap, pixels

  • bits – The bitmap

  • scale – Integer scale, 1 to 8

  • opaque – Paint the clear pixels of the bitmap as the background

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument, an error code of the driver otherwise

esp_err_t pixelfont_fill_rect(const pixelfont_canvas_t *canvas, int x, int y, int width, int height, bool on)

Fill a rectangle.

Parameters:
  • canvas – Drawing surface

  • x – Left edge, pixels

  • y – Top edge, pixels

  • width – Width, pixels

  • height – Height, pixels

  • on – true for the foreground, false for the background

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument, an error code of the driver otherwise

esp_err_t pixelfont_clear(const pixelfont_canvas_t *canvas)

Clear the whole canvas.

Equivalent to filling the whole canvas with the background.

Parameters:

canvas – [in] Canvas

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument, an error code of the driver otherwise

esp_err_t pixelfont_scroll_up(const pixelfont_canvas_t *canvas, int x, int y, int width, int height, int pixels)

Scroll a rectangle up by pixels.

The pixels of the rectangle move up, the rows that leave it at the top are lost, and the rows that become free at the bottom are filled with the background. Useful for a text area that behaves like a terminal: draw a new line in the free rows, then scroll by the height of the line.

The canvas must have its own buffer, so a canvas that sends the picture to a driver block by block cannot be scrolled.

Parameters:
  • canvas – [in] Canvas with a buffer

  • x – Left edge of the rectangle, pixels

  • y – Top edge of the rectangle, pixels

  • width – Width of the rectangle, pixels

  • height – Height of the rectangle, pixels

  • pixels – Distance, pixels; 0 does nothing, height or more clears the rectangle

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument, ESP_ERR_INVALID_STATE when the canvas has no buffer

esp_err_t pixelfont_scroll_down(const pixelfont_canvas_t *canvas, int x, int y, int width, int height, int pixels)

Scroll a rectangle down by pixels.

The mirror image of pixelfont_scroll_up(): the pixels move down, the rows that leave the rectangle at the bottom are lost, and the free rows at the top become the background.

Parameters:
  • canvas – [in] Canvas with a buffer

  • x – Left edge of the rectangle, pixels

  • y – Top edge of the rectangle, pixels

  • width – Width of the rectangle, pixels

  • height – Height of the rectangle, pixels

  • pixels – Distance, pixels; 0 does nothing, height or more clears the rectangle

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument, ESP_ERR_INVALID_STATE when the canvas has no buffer

esp_err_t pixelfont_text_width(const pixelfont_t *font, const char *text, const pixelfont_style_t *style, int *width)

Width of a text in pixels.

Parameters:
  • font – [in] Font

  • text – [in] NUL-terminated UTF-8 string, may be empty

  • style – [in] Drawing style, NULL for PIXELFONT_STYLE_DEFAULT

  • width – [out] Width in pixels, 0 for an empty string

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument, ESP_ERR_INVALID_SIZE for a bad scale

esp_err_t pixelfont_text_height(const pixelfont_t *font, const pixelfont_style_t *style, int *height)

Height of the cells of a font, scaled.

Parameters:
  • font – [in] Font

  • style – [in] Drawing style, NULL for PIXELFONT_STYLE_DEFAULT

  • height – [out] Height in pixels

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument, ESP_ERR_INVALID_SIZE for a bad scale

esp_err_t pixelfont_find_glyph(const pixelfont_t *font, uint32_t codepoint, const pixelfont_glyph_t **glyph)

Find a glyph.

Parameters:
  • font – [in] Font

  • codepoint – [in] Unicode code point

  • glyph – [out] The glyph

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument, ESP_ERR_NOT_FOUND if the font has no such code point

esp_err_t pixelfont_load(const char *path, pixelfont_t **font)

Load a font from a file.

The format is recognised by the content, the usual extensions are only a hint. Supported formats:

  • BDF (X11 bitmap distribution format), text: the cell is taken from FONTBOUNDINGBOX, the advance from DWIDTH, and the glyph bitmaps are placed in the cell. Proportional fonts are supported: every glyph keeps its own advance.

  • PSF1 and PSF2 (Linux console fonts), binary: the cell is 8 pixels wide for PSF1 and arbitrary for PSF2, the advance is the cell width. When the font carries a Unicode table, the glyphs are indexed by it, otherwise the glyph index is the code point (so a PSF1 font without a table covers Latin-1).

Compressed files (.bdf.gz, .psfu.gz) are not read: unpack them first, or use tools/pixelfont.py, which accepts gzip and generates the font for the build.

PCF is not read directly: convert it with pcf2bdf first.

The whole file is read into the heap, so the font lives until pixelfont_free(). A file that does not fit into the heap is rejected with ESP_ERR_NO_MEM: use tools/pixelfont.py to cut the font down to the characters that are actually needed.

Parameters:
  • path – [in] Path of the file

  • font – [out] Loaded font

Returns:

ESP_OK on success, ESP_ERR_INVALID_ARG for a bad argument, ESP_ERR_NOT_FOUND if the file cannot be opened, ESP_ERR_INVALID_RESPONSE if the content is not a supported font, ESP_ERR_NO_MEM if there is not enough memory

void pixelfont_free(pixelfont_t *font)

Free a font loaded with pixelfont_load()

Fonts generated at build time live in the flash and must not be freed.

Parameters:

font – Font, NULL is allowed

struct pixelfont_canvas_t
#include <pixelfont.h>

A drawing surface.

There are two ways to use it. With a buffer (pixelfont_canvas_new(), or the buffer of the display driver attached by hand) the pixels are written into that buffer and the driver sends it to the display when it likes, so a text may be drawn over a picture. Without a buffer the renderer composes the pixels of a glyph or of a bitmap and hands them over to the flush callback block by block, which suits displays that cannot be read back.

The size is used for clipping and may be zero, in which case nothing is clipped.

Public Members

int width

Width of the surface, pixels, 0 to disable clipping.

int height

Height of the surface, pixels, 0 to disable clipping.

pixelfont_pack_t pack

Layout of the buffer and of the blocks passed to flush()

pixelfont_flush_t flush

Writes a block to the display, may be NULL with a buffer.

void *ctx

Passed to flush()

uint8_t *data

Buffer in the packing, may be NULL.

size_t size

Size of the buffer, bytes.

int clip_x

Left edge of the clip rectangle, pixels.

int clip_y

Top edge of the clip rectangle, pixels.

int clip_w

Width of the clip rectangle, 0 to disable clipping.

int clip_h

Height of the clip rectangle, 0 to disable clipping.

struct pixelfont_glyph_t
#include <pixelfont.h>

One glyph of a font.

The glyphs of a font are sorted by code point, so the renderer finds them with a binary search.

Public Members

uint32_t codepoint

Unicode code point.

uint32_t offset

Offset of the bitmap in pixelfont_t.bitmaps, bytes.

uint8_t advance

Advance width of the glyph, pixels.

uint8_t reserved[3]

Alignment.

struct pixelfont_t
#include <pixelfont.h>

A font.

The bitmaps are one bit per pixel, row-major, the most significant bit is the leftmost pixel, every row occupies (width + 7) / 8 bytes. A font is either generated at build time into the flash (see tools/pixelfont.py) or loaded from a file at run time with pixelfont_load().

The cell is the bounding box of the font: the widest glyph and the tallest one. Glyphs are placed in the cell by the loader, so the renderer never needs the per-glyph offsets of the source format.

Public Members

uint8_t width

Width of the cell, pixels.

uint8_t height

Height of the cell, pixels.

int8_t ascent

Pixels above the baseline.

uint16_t count

Number of glyphs.

const pixelfont_glyph_t *glyphs

Glyphs, sorted by code point.

const uint8_t *bitmaps

Glyph bitmaps.

void *owned

Heap block of a font loaded from a file, NULL otherwise.

struct pixelfont_style_t
#include <pixelfont.h>

How to draw a text.

Public Members

uint8_t scale

Integer scale, 1 to 8.

uint8_t spacing

Extra pixels between the cells, not scaled.

bool opaque

Paint the background of the cells as well.

bool reversed

Swap the foreground and the background.