python pil 绘制文本偏移量

问题描述 投票:0回答:3

我尝试使用 Python PIL 在图像上绘制字符。对于 ImageDraw.Draw.text() 函数,xy 参数指向文本的左上角。但是我将 xy 设置为 (0,0),角色还没有绘制在图像的左上角。

from PIL import ImageFont, ImageDraw, Image 

imageSize=(40,40)
mage = Image.new("RGB", imageSize, (0,0,0))
draw = ImageDraw.Draw(image)
txt = "J"
font = ImageFont.truetype("ANTQUAB.ttf",35)
draw.text((0,0), txt, font=font) 

为什么?

python python-imaging-library offset
3个回答
2
投票

xy
draw.text()
参数是文本的左上角 (docs),但是字体在文本周围可能有一些填充,尤其是垂直方向。我所做的是将元组的
y
部分设置为负数(可能在 -5 左右?),它对我有用。


1
投票

看起来有特定于字体的偏移量;您可以从 FreeTypeFont.getbbox() 返回的“顶部”值获取垂直偏移。从 draw.text 调用中的 y 坐标中减去此偏移量将使文本顶部与图像顶部对齐。

from PIL import ImageFont, ImageDraw, Image

text = 'J'
font = "arial.ttf"
fontsize = 12

img_w = 100
img_h = 100
canvas = Image.new('RGBA', size=(img_w,img_h), color='white')
draw = ImageDraw.Draw(canvas)
y_text = 0

font_obj = ImageFont.truetype(font, fontsize)
(left, top, right, bottom) = font_obj.getbbox(text)

x_pos = 0
y_pos = 0

# offset the y coordinate in the draw call by the "top" parameter fromgetbbox; this is the font-specific text padding
draw.text(xy=(x_pos, y_pos-top), 
            text=text, 
            font=font_obj,
            align='left', 
            fill='black')

canvas.show()

0
投票

此代码:

from PIL import ImageFont, ImageDraw, Image 

imageSize=(100,100)
image = Image.new("RGB", imageSize, (0,0,0))
draw = ImageDraw.Draw(image)
txt = "J"
font = ImageFont.truetype("ARIAL.ttf",35)
draw.text((0,0), txt, font=font) 
image.show()

生成这个:

enter image description here

这不是你所期待的吗?

© www.soinside.com 2019 - 2024. All rights reserved.