How do you size a background to the rendered text bounds?

textbbox returns the text bounding box for a font and anchor. Its top and left offsets need not be zero.

Pixel experiment and interpretation

For a label background subtract left from right and top from bottom, retaining the offsets. Measure and draw with the same font because metrics differ between files.

from PIL import Image, ImageDraw, ImageFont

d=ImageDraw.Draw(Image.new('L',(80,30)))
a,b,c,e=d.textbbox((0,0),'Ag',font=ImageFont.load_default())
(c>a,e>b)

Result (True, True)

中文

怎样为字体留出真实字形所占的空间?

textbbox 返回给定字体与锚点下的文本外接矩形,起始偏移不一定为零。

像素实验与适用边界

做标签底色时用右减左、下减上计算尺寸,并保留偏移。不同字体文件可产生不同数值,因此用同一字体测量和绘制。

from PIL import Image, ImageDraw, ImageFont

d=ImageDraw.Draw(Image.new('L',(80,30)))
a,b,c,e=d.textbbox((0,0),'Ag',font=ImageFont.load_default())
(c>a,e>b)

结果 (True, True)

References / 参考来源

Keep reading / 继续阅读