I am drawing text atop a base image via PIL
. One of the requirements is for it to overflow to the next line(s) if the combined width of all characters exceeds the width of the base image.
Currently I'm using textwrap.wrap(text, width=16)
to accomplish this. Here width
defines the number of characters to accommodate in one line. Now the text can be anything since it's user generated. So the problem is that hard-coding width
won't take into account width
variability due to font type, font size and character selection.
What do I mean?
Well imagine I'm using DejaVuSans.ttf
, size 14. A W
is 14 in length, whereas an 'i' is 4. For a base image of width 400, up to 100 i
characters can be accommodated in a single line. But only 29 W
characters. I need to formulate a smarter way of wrapping to the next line, one where the string is broken when the sum of character-widths exceeds the base image width.
Can someone help me formulate this? An illustrative example would be great!
If precision matters for you, the best way to get the real text width is to actually render it, since font metrics are not always linear, regarding the kerning or the font size (see here) for example, and therefore not easily predictable. We can approach the optimal breakpoint with ImageFont method
get_size
that internally uses core font rendering methods (see PIL github)and use it like so:
Since you know the width of each character, you should make that into a dictionary, from which you get the widths to calculate the stringwidth:
From here you can lookup each letter and use that sum to check your width: