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

2024-05-10 05:58:14 发布

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

如果已知字体(例如“Times New Roman”)和大小(例如12 pt),则如何计算字符串(例如“Hello world”)的长度(可能仅为大约像素)?

我需要这样做一些在Windows应用程序中显示的文本的手动右对齐,所以我需要调整数字空间来获得对齐。


Tags: 字符串文本pt应用程序hellonewworldwindows
2条回答

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

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

打印(x,y)大小为:

(58, 11)

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

这将显示:

(47, 12)
(45, 12)

相关问题 更多 >