如果您精確的問題,才能獲得真正的文本的寬度最好的方法是實際渲染它,因爲字體規格並不總是線性的,關於字距或字體大小(見例如,here)不容易預測。 我們可以接近與ImageFont方法get_size
在內部使用核心字體渲染方法的最佳斷點(見PIL github)
def break_text(txt, font, max_width):
# We share the subset to remember the last finest guess over
# the text breakpoint and make it faster
subset = len(txt)
letter_size = None
text_size = len(txt)
while text_size > 0:
# Let's find the appropriate subset size
while True:
width, height = font.getsize(txt[:subset])
letter_size = width/subset
# min/max(..., subset +/- 1) are to avoid looping infinitely over a wrong value
if width < max_width - letter_size and text_size >= subset: # Too short
subset = max(int(max_width * subset/width), subset + 1)
elif width > max_width: # Too large
subset = min(int(max_width * subset/width), subset - 1)
else: # Subset fits, we exit
break
yield txt[:subset]
txt = txt[subset:]
text_size = len(txt)
,並使用它,像這樣:
from PIL import Image
from PIL import ImageFont
img = Image.new('RGBA', (100, 100), (255,255,255,0))
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("Helvetica", 12)
text = "This is a sample text to break because it is too long for the image"
for i, line in enumerate(break_text(text, font, 100)):
draw.text((0, 16*i), line, (255,255,255), font=font)
或如何使用'font.getsize( c)[0]'在飛行中,爲每個字符'c'? –
如果你這樣做的話,這可能會奏效:'current_width = sum([font.getsize(c)[0] for c in word])' - 如果你可以創建一個字典,訪問速度比做這個函數調用要快每一次。 – JacobIRR
感謝您的提示。 –