Wrap text and adjust font to container in PIL?

北城余情 提交于 2021-02-15 07:50:57

问题


I want to create a program for making a bingo, and I have everything set up except putting the text, which may range from a single word to even a whole sentence, into each field. How would I go about wrapping that text and adjusting the font size so it fits into each field?


回答1:


I don't know of a way of auto-sizing text with PIL, but you can do it with wand. I am not that experienced with wand, but you can use the caption() method if you want your text auto-wrapped and sized. I changed the code between runs to write a small amount of text and a considerably longer text in an area I marked in white:

#!/usr/bin/env python3

from wand.image import Image
from wand.drawing import Drawing
from wand.font import Font

# Create a red canvas 600x300
with Image(width=600, height=300, pseudo='xc:red') as canvas:
    left, top, width, height = 10, 20, 400, 150
    with Drawing() as context:
        context.fill_color = 'white'
        context.rectangle(left=left, top=top, width=width, height=height)
        font = Font('/System/Library/Fonts/MarkerFelt.ttc')
        context(canvas)
        canvas.caption('Considerably longer text that will need a smaller font and some wrapping too', left=left, top=top, width=width, height=height, font=font, gravity='center')
    canvas.save(filename='result.png')

There are examples of more sophisticated wrapping techniques using Python's textwrap in the wand documentation.

Keywords: wand, image processing, python, caption, auto-wrap, auto-size, word wrap.



来源:https://stackoverflow.com/questions/63087748/wrap-text-and-adjust-font-to-container-in-pil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!