首页 > 解决方案 > font.getsize() 似乎不适用于参数内的“\n”(新行)

问题描述

使用的字体:https ://www.fontspace.com/abeezee-font-f30774

ImageFont.truetype(*path/to/font*, 300)
font.getsize("1\n\r0\n\r9")  # returns: (1080, 280) which is wrong!
image = np.full(shape=(1, 1, 3), fill_value=0, dtype=np.uint8)
image = Image.fromarray(image, mode="RGB")
draw = ImageDraw.Draw(image)
draw.multiline_textsize(text="1\n\r0\n\r9", font=font, spacing=0)  # returns: (180, 837) which is correct"

为什么结果不一样?我错过了什么?

标签: python-3.xpython-imaging-library

解决方案


所以主要错误是:1)对于多行文本,我们应该使用:

 PIL.ImageDraw.ImageDraw.multiline_text(xy, text, fill=None, font=None, anchor=None, spacing=0, align="left", direction=None, features=None, language=None) 

此外 .getsize() 返回的高度有点太大了。对我有用的高度是:

font.getmask(digit).size[1]

这与以下内容相同:

font.getsize(digit)[1] - font.getoffset(digit)[1]

推荐阅读