编辑:添加完整的工作示例
我有以下程序:
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")
这会生成以下图像:
似乎在编写文本时,PIL库在顶部添加了一些边距.此边距取决于我使用的字体.
如何在尝试定位文本时考虑到这一点(我希望它位于矩形的中间)?
(在Ubuntu 14.04上使用Pillow 2.3.0的Python 2.7.6)
我不明白为什么,但减去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")