正确居中文本 (PIL/Pillow)

Correctly centring text (PIL/Pillow)

我在黑色条带上绘制一些文本,然后使用 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

现在说完一切,结果如下所示:

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

记得将你的font作为第二个参数传递给draw.textsize(还要确保你真的使用相同的textfont参数给draw.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!")

结果: