您可以直接计算宽度,而不是渲染到图像缓冲区并计算像素使用字体规格。似乎没有随核心 python 一起分发的字体 API,但在各种软件包中都有大量第三方字体 API。这是一个相当完整的解决方案对于 Adobe 字体规格,使用matplotlib
:
>>> from matplotlib import rcParams
>>> import os.path
>>> afm_filename = os.path.join(rcParams['datapath'], 'fonts', 'afm', 'ptmr8a.afm')
>>>
>>> from matplotlib.afm import AFM
>>> afm = AFM(open(afm_filename, "rb"))
>>> afm.string_width_height('What the heck?')
(6220.0, 694)
度量以所使用字体的比例因子(点大小)的 1/1000 为单位报告。 (感谢@JacobLee 挖掘这个信息.)
另一种可能性是tkFont
的模块tkinter
. 这一页记录函数tkFont.Font.measure("some string")
,但似乎你需要一个 Tk 窗口才能使用它;所以我不知道它有多实用:
# Python 3 names -- see Note below
import tkinter
from tkinter import font as tkFont
tkinter.Frame().destroy() # Enough to initialize resources
arial36b = tkFont.Font(family='Arial', size=36, weight='bold')
width = arial36b.measure("How wide is this?")
print(width) # Prints: 404
注意:在 python 2 中(以及在page我上面提到过),tkinter
被称为Tkinter
, and tkinter.font
是一个顶级模块,tkFont
:
import Tkinter
import tkFont