【问题标题】:Correctly centring text (PIL/Pillow)正确居中文本(PIL/Pillow)
【发布时间】:2017-09-29 12:49:52
【问题描述】:

我正在黑色条上绘制一些文本,然后使用PIL 将结果粘贴到基础图像之上。一个关键是使文本位置完美地位于黑条的中心。

我通过以下代码满足这一点:

from PIL import Image, ImageFont, ImageDraw

background = Image.new('RGB', (strip_width, strip_height)) #creating the black strip
draw = ImageDraw.Draw(background)
font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSansBold.ttf", 16)
text_width, text_height = draw.textsize("Foooo Barrrr!")
position = ((strip_width-text_width)/2,(strip_height-text_height)/2)
draw.text(position,"Foooo Barrrr!",(255,255,255),font=font)
offset = (0,base_image_height/2)
base_image.paste(background,offset)

注意我是如何设置position 的。

现在说了这么多,结果如下:

文本没有精确居中。它稍微向右和向下。如何改进我的算法?

【问题讨论】:

  • text的内容是什么? “Foooo Barrrr!”??为什么在调用 draw.textsize 时使用text,而在调用 draw.text 时使用新的字符串文字?
  • draw.textsize 不知道您使用的字体。我认为您应该将其作为第二个参数传递。也许您需要返回文档,或提供一个最小示例。
  • @tiwo: text 打错了,应该是"Foooo Barrrr!"。我已经在问题中解决了它。

标签: python python-imaging-library pillow


【解决方案1】:

记得将 font 作为第二个参数传递给 draw.textsize(并确保您确实使用相同的 textfont 参数来绘制.textsize 和 draw.text)。

这对我有用:

from PIL import Image, ImageFont, ImageDraw

def center_text(img, font, text, color=(255, 255, 255)):
    draw = ImageDraw.Draw(img)
    text_width, text_height = draw.textsize(text, font)
    position = ((strip_width-text_width)/2,(strip_height-text_height)/2)
    draw.text(position, text, color, font=font)
    return img

用法:

strip_width, strip_height = 300, 50
text = "Foooo Barrrr!!"

background = Image.new('RGB', (strip_width, strip_height)) #creating the black strip
font = ImageFont.truetype("times", 24)
center_text(background, font, "Foooo Barrrr!")

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2018-01-10
    • 2013-10-12
    • 2014-01-27
    • 2016-05-25
    • 1970-01-01
    • 2010-12-30
    相关资源
    最近更新 更多