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

后端 未结 2 421
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-24 16:25

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 w

2条回答
  •  广开言路
    2021-01-24 17:00

    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])
    

提交回复
热议问题