为什么ImageFont.getsize()在使用单间距字体时测量字符不一致?

2024-05-16 01:41:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图计算单间距字体中字形的宽度和高度(我希望是一致的),但是ImageFont.getsize()返回不同的值,给定不同的单个字符串:

>>> from PIL import ImageFont
>>> font = ImageFont.truetype("consola.ttf", size=15)
>>> font.getsize(".")
(8, 12) 
>>> font.getsize("@")
(9, 15)

ImageFont.getlength(),另一方面,确实总是为每个字符返回相同的宽度:

>>> font.getlength("@")
8.0
>>> font.getlength(".")
8.0

那么什么是getsize()测量,为什么它与getlength()不同呢


Tags: 字符串fromimport宽度pil高度字体font
1条回答
网友
1楼 · 发布于 2024-05-16 01:41:04

ImageFont.py文件:

getlength():

Returns length (in pixels with 1/64 precision) of given text when rendered in font with provided direction, features, and language. This is the amount by which following text should be offset. Text bounding box may extend past the length in some fonts, e.g. when using italics or accents. The result is returned as a float; it is a whole number if using basic layout.

getsize():

Returns width and height (in pixels) of given text if rendered in font with provided direction, features, and language.

该文件将差异解释为:

Use :py:meth:getlength() to measure the offset of following text with 1/64 pixel precision.

我从中了解到getlength()返回当前文本和后续文本之间的偏移量(空格),而getsize()返回当前(输入)文本的实际尺寸

从ConsoleA字体系列website

... a monospaced font is specified. All characters have the same width ...

这意味着每个字符的宽度应该相同,并且每个字符与下一个字符的间距应该相同。可以在以下脚本中看到:

import PIL
from PIL import ImageFont
font = ImageFont.truetype("consola.ttf",size=15)
print(font.getsize("a"))
print(font.getsize("h"))
print(font.getsize("g"))
print(font.getsize("z"))
print(font.getsize("."))
print(font.getsize("@"))
print(font.getlength("a"))
print(font.getlength("h"))
print(font.getlength("g"))
print(font.getlength("z"))
print(font.getlength("."))
print(font.getlength("@"))

哪些产出:

(8, 12)
(8, 12)
(8, 15)
(8, 12)
(8, 12)
(9, 15)
8.0
8.0
8.0
8.0
8.0
8.0

几乎每个字符都有8的宽度和8的偏移量,但是它们的高度不同,因为有些字符有延伸部分,例如向下延伸的“g”部分。唯一的例外是宽度为9的“@”,对此我找不到任何理由

相关问题 更多 >