【发布时间】: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