如何在 Pillow 中添加文本对齐对齐?

How to add text-align justify in Pillow?

我有一个使用换行的代码,但我想添加 text-align: justify 以填充整个图像。我该怎么做?

from PIL import Image, ImageDraw, ImageFont
import textwrap

astr = 'Python '
para = textwrap.wrap(astr*100, width=15)

MAX_W, MAX_H = 200, 200
im = Image.new('RGB', (MAX_W, MAX_H), (0, 0, 0, 0))
draw = ImageDraw.Draw(im)
font = ImageFont.truetype('arial.ttf', 18)

current_h, pad = 0, 0
for line in para:
    w, h = draw.textsize(line, font=font)
    draw.text(((MAX_W - 1.7*w) / 2, current_h), line, font=font)
    current_h += h + pad

im

输出:

我不相信有像 text-align: justify in pillow 这样的选项,但你可以通过硬编码你需要的东西来做到这一点。

代码:

from PIL import Image, ImageDraw, ImageFont
import textwrap


im = Image.new('RGB', (200, 200), (0, 0, 0, 0))
draw = ImageDraw.Draw(im)


astr = 'Python '
font = ImageFont.truetype('arial.ttf', 15)
num_row = 4


draw.text((0,0), astr * num_row, font=font)
draw.text((0,30), astr * num_row, font=font)
draw.text((0,60), astr * num_row, font=font)
draw.text((0,90), astr * num_row, font=font)
draw.text((0,120), astr * num_row, font=font)
draw.text((0,150), astr * num_row, font=font)
draw.text((0,180), astr * num_row, font=font)
im

输出:

注意 - 您可以更改字体大小以及每行中 python 出现的次数,以使其适合您想要的图像。