2016-03-03 74 views
0

如果字体,例如“Times New Roman”和大小,例如已知12英尺长的绳子的长度如何“你好世界”以像素为单位进行计算,也许只有大约?如何计算特定字体和大小的字符串长度(以像素为单位)?

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

+2

查看https://pillow.readthedocs.org/en/3.0.0/reference/ImageFont.html#PIL.ImageFont.PIL.ImageFont.ImageFont.getsize – Selcuk

回答

3

另一种方法是问的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) 
+0

谢谢;必须添加'()'以便在Python 3上使用print,但否则它会起作用。但奇怪的是,这两种方法之间存在显着的x尺寸差异。 – EquipDev

+1

您可以从给定的字体获取相当多的维度,所以我猜测'getsize()'使用了另一个维度。 –

+0

我得到AttributeError:模块'ctypes'没有属性'windll'。这很奇怪,因为当我在ctypes之后点击'w'时,python会在弹出框中显示该方法。 – bobsmith76

7

基于从@Selcuk评论,我找到了一个答案:

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

其照片(X,Y)尺寸:

(58, 11)

+0

根据这个网站,Python中不支持PIL模块3然而http://www.pythonware.com/products/pil/。所以我无法让上面的工作。 – bobsmith76

+0

这可以通过安装Pillow(PIL的现代更新版本)在Python3上运行。 https://pillow.readthedocs.io有安装说明(“pip install Pillow”)。 – mcherm

相关问题