如何计算特定字体和大小的字符串长度(以像素为单位)?

Equ*_*Dev 5 python windows fonts python-3.x

如果字体,例如"Times New Roman"和大小,例如12 pt,是已知的,那么如何以像素计算字符串的长度,例如"Hello world",可能只是大约?

我需要这个来对Windows应用程序中显示的文本进行一些手动右对齐,所以我需要调整数字空格以获得对齐.

Equ*_*Dev 16

根据@Selcuk的评论,我找到了一个答案:

from PIL import ImageFont
font = ImageFont.truetype('times.ttf', 12)
size = font.getsize('Hello world')
print(size)
Run Code Online (Sandbox Code Playgroud)

其打印(x,y)大小为:

(58,11)

  • 通过安装Pillow(PIL的现代更新版本)在Python3上对我有效。https://pillow.readthedocs.io具有安装说明(“ pip install Pillow”)。 (2认同)

Mar*_*ans 6

另一种方法是询问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)

print(GetTextDimensions("Hello world", 12, "Times New Roman"))
print(GetTextDimensions("Hello world", 12, "Arial"))
Run Code Online (Sandbox Code Playgroud)

这将显示:

(47, 12)
(45, 12)
Run Code Online (Sandbox Code Playgroud)