Wrap text according to font width in CircuitPython

I wrote a small function called wrap_text which re-wraps a block of text so that, when rendered in a given font, it is no more than a given number of pixels wide. (There are other functions available for wrapping text according to the number of letters but when the letter "l" is much narrower than the letter "w", this can give unsatisfactory results on specific texts)

The program splits the input string on any whitespace, then uses a simple "greedy" algorithm to add each word to the current line if it fits, otherwise break and continue with the next line.

The indentation of the first and subsequent lines can be specified; the default indents the 2nd line because my use case was to wrap text of a poem.

A new string is returned, with newlines inserted in the required spots, suitable for use with a standard circuitpython label.

The sample program is for the Adafruit MagTag. It uses this function to display a poem (placed in CIRCUITPY/poem.txt) 5 lines at a time, updating once per hour. The first line in poem.txt is always displayed at the bottom, and is intended to hold the poem's name and author. By using deep sleep mode, I expect that I'll only need to charge the device every few days.

I wrote this because I was very moved by Amanda Gorman's poem "The Hill We Climb". I could tell this was a poem that would really "stick with me" and wanted the opportunity to experience the poem over a longer period of time. I can look at the MagTag several times a day and reflect on whatever lines happen to be visible at the moment.

Out of respect for Ms. Gorman's copyright I don't include the poem's full text here. However, many news outlets have quoted it in its entirety. And, of course, you can put whatever you like in poem.txt—Why not something by Maya Angelou or Lin-Manuel Miranda, apparently two people who Ms. Gorman has found inspiring.

"Festive" 3D printed stand on thingiverse

Files currently attached to this page:

helvB12.pcf6.6kB
helvBO12.pcf12.7kB



Entry first conceived on 23 January 2021, 16:42 UTC, last modified on 23 January 2021, 17:21 UTC
Website Copyright © 2004-2021 Jeff Epler