使用Pillow/Python对齐文本

5

我正在使用Python 3中的Pillow 7.2.0将文本插入具有固定大小的图像中。

我现在想要在特定宽度中插入具有固定字体和字号的文本,并使其两端对齐,就像一个固定的文本框。文本应在文本框内对齐,以便触及左右端点。我没有看到任何关于如何做到这一点的文档。

最合理的方法是什么?

我希望它能够水平压缩文本以适应文本框而不创建第二行,尽管这种情况很少发生。

另外,我正在查看Pillow的文档,并想知道锚点参数的作用。我没有找到任何解释。

ImageDraw.text(... anchor=None, ...)

锚点参数在Pillow 8.0.0之前被忽略。现在它用于指定xy参数应如何与文本对齐。文档在此处:https://pillow.readthedocs.io/en/stable/handbook/text-anchors.html - Nulano
1个回答

6

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

example of justified text


请问您能否编辑这部分代码,以便在文本小部件中获得输出(而不是作为图像)? - sonny
@Sonny 文本小部件? OP的问题是关于Pillow,这是一个处理图像而不是小部件的库... 你可能想要在你的GUI框架中搜索一个涉及到的答案,而不是Pillow。 - Nulano
好的先生。我尝试在文本小部件上对一些文本内容进行调整。您需要帮助吗? - sonny
@sonny 不好意思,我不知道你用什么框架来创建你的“文本小部件”。请提出一个新问题,并提供必要的细节。参考链接:https://stackoverflow.com/help/how-to-ask - Nulano
https://stackoverflow.com/questions/76893172/how-to-text-justify-in-python?noredirect=1#comment135560526_76893172 - sonny

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接