python PIL draw multiline text on image

后端 未结 6 1098
野的像风
野的像风 2020-12-04 10:14

I try to add text at the bottom of image and actually I\'ve done it, but in case of my text is longer then image width it is cut from both sides, to simplify I would like te

6条回答
  •  生来不讨喜
    2020-12-04 10:40

    You could use textwrap.wrap to break text into a list of strings, each at most width characters long:

    import textwrap
    lines = textwrap.wrap(text, width=40)
    y_text = h
    for line in lines:
        width, height = font.getsize(line)
        draw.text(((w - width) / 2, y_text), line, font=font, fill=FOREGROUND)
        y_text += height
    

提交回复
热议问题