本文介绍了如何计算特定字体和大小的字符串长度(以像素为单位)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果是字体,例如"Times New Roman"及其大小,例如已知12 pt的字符串长度如何"Hello world"以像素为单位进行计算,也许仅是近似值?

If the font, e.g. "Times New Roman", and size, e.g. 12 pt, is known, how can the length of a string, e.g. "Hello world" be calculated in pixels, maybe only approximately?

我需要执行此操作以对Windows应用程序中显示的文本进行一些手动右对齐,因此我需要调整数字空间以获取对齐方式.

I need this to do some manual right alignment of text shown in an Windows application, so I need to adjust the number spaces to get the alignment.

推荐答案

另一种方法是如下询问Windows:

An alternative is to ask Windows as follows:

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)

这篇关于如何计算特定字体和大小的字符串长度(以像素为单位)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-03 15:32