Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
759 views
in Technique[技术] by (71.8m points)

python - Wrap text and adjust font to container in PIL?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here

enter image description here

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...