如果字体,例如“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/