2016-03-03 94 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

相關問題