Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...