正确居中文本(PIL/Pillow)

Has*_*aig 5 python python-imaging-library 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)
Run Code Online (Sandbox Code Playgroud)

注意我是如何设置的position

现在一切都说了又做了,结果看起来像这样:

在此处输入图片说明

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

tiw*_*iwo 9

请记住,你传递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
Run Code Online (Sandbox Code Playgroud)

用法:

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!")
Run Code Online (Sandbox Code Playgroud)

结果:

foob​​arrrr