正确居中文本(PIL /枕头)

哈桑·拜格(Hassan Baig)

我正在黑条上绘制一些文本,然后使用将结果粘贴到基本图像的顶部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!")

结果:

fooobarrrr

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章