pho*_*hos 6 python-imaging-library python-3.x
我在 Python 3 中使用 Pillow 7.2.0 将文本插入到固定大小的图像中。
我现在想将具有固定字体和字体大小的文本插入特定宽度并使其对齐,就像固定文本框一样。文本应该在文本框中对齐,以便它触及左端和右端。我没有看到任何有关如何执行此操作的文档。
做到这一点最合理的方法是什么?
我确实希望它能够水平压缩文本以适合文本框,而无需创建第二行,尽管这种情况很少见。
作为旁注,我正在浏览 Pillow 的文档,并且想知道锚参数的作用。我没有找到任何解释。
ImageDraw.text(... anchor=None, ...)
Run Code Online (Sandbox Code Playgroud)
Pillow 没有内置的方法来对齐文本。对齐文本的最佳方法是将其按空格分隔,然后插入空格来填充剩余空间。
from PIL import Image, ImageDraw, ImageFont
font = ImageFont.truetype("arial.ttf", 20)
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n"\
"Pellentesque accumsan nec felis ut vulputate."
image_width = 600
im = Image.new("RGB", (image_width, 80), "white")
d = ImageDraw.Draw(im)
y = 10
for line in text.split("\n"):
words = line.split(" ")
words_length = sum(d.textlength(w, font=font) for w in words)
space_length = (image_width - words_length) / (len(words) - 1)
x = 0
for word in words:
d.text((x, y), word, font=font, fill="black")
x += d.textlength(word, font=font) + space_length
y += 30
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
572 次 |
| 最近记录: |