Search code examples
pythonword-wraptext-processing

Breaking string into multiple lines according to character width (python)


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!


Solution

  • 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:

    char_widths = {
        'a': 9,
        'b': 11,
        'c': 13,
        # ...and so on
    }
    

    From here you can lookup each letter and use that sum to check your width:

    current_width = sum([char_widths[letter] for letter in word])