在 PIL 中包裹文本并调整字体到容器?

Icy*_*ear 1 python python-imaging-library

我想创建一个用于制作宾果游戏的程序,除了将文本(范围可以从单个单词到甚至整个句子)放入每个字段之外,我已经设置了所有内容。我将如何包装该文本并调整字体大小以使其适合每个字段?

Mar*_*ell 6

我不知道使用 PIL 自动调整文本大小的方法,但你可以使用wand来做到这一点。我对 的经验不是很丰富,但如果您希望文本自动换行和调整大小,wand则可以使用该方法。caption()我更改了运行之间的代码,在我用白色标记的区域中写入少量文本和相当长的文本:

#!/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')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在此输入图像描述

textwrapwand文档中有使用 Python 的更复杂的包装技术的示例。

关键词:wand、图像处理、python、标题、自动换行、自动大小、自动换行。