Python图像库 - 字体定位

时间:2016-01-04 18:46:52

标签: python python-imaging-library

编辑:添加了完整的工作示例

我有以下程序:

from PIL import Image, ImageDraw, ImageFont

FULL_SIZE = 50
filename = 'font_test.png'
font="/usr/share/fonts/truetype/msttcorefonts/arial.ttf"
text="5"

image = Image.new("RGBA", (FULL_SIZE, FULL_SIZE), color="grey")
draw = ImageDraw.Draw(image)
font = ImageFont.truetype(font, 40)
font_width, font_height = font.getsize(text)
draw.rectangle(((0, 0), (font_width, font_height)), fill="black")
draw.text((0, 0), text, font=font, fill="red")
image.save(filename, "PNG")

这会生成以下图像:

enter image description here

似乎在编写文本时,PIL库会在顶部添加一些边距。此边距取决于我使用的字体。

如何在尝试定位文本时考虑到这一点(我希望它位于矩形的中间)?

(在Ubuntu 14.04上使用Pillow 2.3.0的Python 2.7.6)

1 个答案:

答案 0 :(得分:5)

我不明白为什么,但从font.getoffset(text)[1]坐标中减去y会将其修复到我的计算机上。

from PIL import Image, ImageDraw, ImageFont

FULL_SIZE = 100
filename = 'font_posn_test.png'
fontname = '/usr/share/fonts/truetype/msttcorefonts/arial.ttf'
textsize = 40
text = "5"

image = Image.new("RGBA", (FULL_SIZE, FULL_SIZE))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype(fontname, textsize)
print font.getoffset(text)
print font.font.getsize(text)
font_width, font_height = font.getsize(text)

font_y_offset = font.getoffset(text)[1] # <<<< MAGIC!

draw.rectangle(((0, 0), (font_width, font_height)), fill="black")
draw.text((0, 0 - font_y_offset), text, font=font, fill="red")
image.save(filename, "PNG")