如果您使用的是Windows,则可以使用以下方法.
它使用当前屏幕作为输出上下文,并计算在给定点大小下显示给定字体所需的尺寸.它返回一个包含文本宽度和文本高度的元组:
import ctypes
def GetTextDimensions(text, points, font):
class SIZE(ctypes.Structure):
_fields_ = [("cx", ctypes.c_long), ("cy", ctypes.c_long)]
hdc = ctypes.windll.user32.GetDC(0)
hfont = ctypes.windll.gdi32.CreateFontA(-points, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, font)
hfont_old = ctypes.windll.gdi32.SelectObject(hdc, hfont)
size = SIZE(0, 0)
ctypes.windll.gdi32.GetTextExtentPoint32A(hdc, text, len(text), ctypes.byref(size))
ctypes.windll.gdi32.SelectObject(hdc, hfont_old)
ctypes.windll.gdi32.DeleteObject(hfont)
return (size.cx, size.cy)
for text, font in [
('....', 'Arial'),
('WWWW', 'Arial'),
('WWWW', 'Arial Narrow'),
('....', 'Courier New'),
('WWWW', 'Courier New'),
("Test", "Unknown font"),
('Test', 'Calibri')]:
print '{:8} {:20} {}'.format(text, font, GetTextDimensions(text, 12, font))
这将显示以下输出:
.... Arial (12, 15)
WWWW Arial (44, 15)
WWWW Arial Narrow (36, 16)
.... Courier New (28, 15)
WWWW Courier New (28, 15)
Test Unknown font (24, 15)
Test Calibri (23, 14)
作为比例字体的Arial显示….和WWWW的不同尺寸,但Courier New是固定宽度给出相同的结果. Arial Narrow给出36,而Arial为44.
对于未知字体,Windows字体映射器已自动选择默认字体.
在Python 2.x上测试过.
Python 3.x的注意事项
由于这是在Windows中调用GetTextExtentPoint32A(),因此需要将ANSI文本传递给它,因此可以按如下方式更改调用以解决此问题:
ctypes.windll.gdi32.GetTextExtentPoint32A(hdc, text.encode('cp1252'), len(text), ctypes.byref(size))
或者,切换代码以使用宽版本,替换为以下两个:
hfont = ctypes.windll.gdi32.CreateFontW(-points, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, font)
ctypes.windll.gdi32.GetTextExtentPoint32W(hdc, text, len(text), ctypes.byref(size))