我正在黑条上绘制一些文本,然后使用将结果粘贴到基本图像的顶部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作为第二个参数(并且确保你真的使用相同text
和font
参数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!")
结果:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句