我使用以下兩種方法來計算一個樣本串的渲染寬度用於一組字體類型和大小:測量文本的寬度(Python的/ PIL)
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 14)
sample = "Lorem ipsum dolor sit amet, partem periculis an duo, eum lorem paulo an, mazim feugiat lobortis sea ut. In est error eirmod vituperata, prima iudicabit rationibus mel et. Paulo accumsan ad sit, et modus assueverit eum. Quod homero adversarium vel ne, mel noster dolorum te, qui ea senserit argumentum complectitur. Duo at laudem explicari deterruisset, eu quo hinc mnesarchum. Vel autem insolens atomorum at, dolorum suavitate voluptatum duo ex."
#METHOD 1
draw_txt = ImageDraw.Draw(img)
width, height = draw_txt.textsize(sample, font=font)
print width
#METHOD 2
width = 0
for c in sample:
width += font.getsize(c)[0]
print width
METHOD 1
產生的寬度3236
,而METHOD 2
得到3270
。爲何差異?此外,我還注意到樣本文本越短,這兩種方法之間的差異越小。
這是怎麼回事?而且哪個寬度可以認爲是true渲染句子的寬度?最後,我可以做兩種方法報告大致相同的寬度嗎?
注:示範文本是長