我在黑色 strip 上绘制一些文本,然后使用 PIL
将结果粘贴到基本图像之上。一个关键是让文本位置完美地位于黑色 strip 的中心。
我通过以下代码来满足这一点:
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!")
结果:
关于python - 正确居中文本 (PIL/Pillow),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43730389/