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

标签 python windows python-3.x fonts

如果字体,例如“Times New Roman”和大小,例如12 pt,是已知的,字符串的长度如何,例如“Hello world”以像素为单位计算,也许只是大约?

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

最佳答案

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

关于python - 如何计算特定字体和大小的字符串长度(以像素为单位)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35771863/

相关文章:

python - 将字符串表达式转换为数学表达式?

python - 如何在 python 中逐个字符地拆分 unicode 字符串?

python - 被 scrapy 困住了,下面是来自 subreddits 的 imgur 链接

c++ - 在 Qt 应用程序中接收 WM_COPYDATA 消息

python - 使用 python 从终端读取字符串

python-3.x - 如何在 Python 3.4 中获取字母表中的字符位置?

python - 如何解析在 python 中实时写入的 JSON 文件?

python - 使用 ChromeDriver 和使用 Selenium 的 Chrome 访问应用程序时,在访问消息之前检查浏览器

php - 保持长时间运行(永远)的 php CLI 进程在 Windows 上运行

c++ - 在 C++ 中访问 Windows 任务栏图标