【发布时间】:2016-06-16 18:15:09
【问题描述】:
如果字体,例如“Times New Roman”和大小,例如12 pt,已知,字符串的长度如何,例如“Hello world” 以像素为单位计算,也许只是近似?
我需要它对 Windows 应用程序中显示的文本进行一些手动右对齐,因此我需要调整数字空格来获得对齐。
【问题讨论】:
标签: python windows python-3.x fonts
如果字体,例如“Times New Roman”和大小,例如12 pt,已知,字符串的长度如何,例如“Hello world” 以像素为单位计算,也许只是近似?
我需要它对 Windows 应用程序中显示的文本进行一些手动右对齐,因此我需要调整数字空格来获得对齐。
【问题讨论】:
标签: python windows python-3.x fonts
根据@Selcuk 的评论,我找到了答案:
from PIL import ImageFont
font = ImageFont.truetype('times.ttf', 12)
size = font.getsize('Hello world')
print(size)
将 (x, y) 大小打印为:
(58, 11)
这是一个函数:
from PIL import ImageFont
def get_pil_text_size(text, font_size, font_name):
font = ImageFont.truetype(font_name, font_size)
size = font.getsize(text)
return size
get_pil_text_size('Hello world', 12, 'times.ttf')
【讨论】:
另一种方法是按如下方式询问 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 3 上使用 print ,否则它可以工作。但奇怪的是,这两种方法之间存在显着的 x 大小差异。
getsize() 使用的是不同的尺寸。