如果精度对您很重要,那么获得真实文本宽度的最佳方法是实际呈现它,因为字体度量并不总是线性的,例如关于字距调整或字体大小(参见 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)