我想要做的是一个函数,通过给定图像width
和height
以及text
将文本放入图像中并使用完美字体大小。
我通过反算法实现了这一点。这是我的代码:
# -*- coding: utf-8 -*-
from PIL import ImageFont
def get_total_area(width, height):
return width * height
def get_font(name, size):
return ImageFont.truetype(font, size)
def fit(width, height, font, size, text):
font = get_font(font, size)
text_w, text_h = font.getsize(text)
text_area = get_total_area(text_w, text_h)
total_area = get_total_area(width, height)
if total_area>text_area:
action(size)
return True
else:
return size
def action(size):
print("Succes!")
counter = 0
text = """One way of doing it is to pass the text with a default font size of, say 20, to imagettfbbox and retrieve the width from it. You can then calculate how much smaller or bigger the text should be to fit the size you want by calculating a scale factor:"""
size = 60
font = 'my-font.ttf'
while True:
counter += 1
ans = fit(500, 500, font, size, text)
if ans == True:
break
else:
size = ans
size -=1
print("Font_Size: {}".format(size))
print("Repetitions: {} ".format(counter))
在这个具体示例中(来自我上面的代码),重复 16 ,完美的字体大小 45 。现在,在StackOverflow中稍微调查一下,我发现了有关同一问题的问题和一个解决方案引起了我的注意:https://stackoverflow.com/a/10689312/5106998
所以我修改了我的代码如下:
# -*- coding: utf-8 -*-
from PIL import ImageFont
def get_total_area(width, height):
return width * height
def get_font(name, size):
return ImageFont.truetype(font, size)
def fit(width, height, font, size, text):
font = get_font(font, size)
text_w, text_h = font.getsize(text)
text_area = get_total_area(text_w, text_h)
total_area = get_total_area(width, height)
if total_area>text_area:
action(size)
return True
else:
scale = total_area/text_area
size = int(round(size*scale))
return size
def action(size):
print("Succes!")
counter = 0
text = """One way of doing it is to pass the text with a default font size of, say 20, to imagettfbbox and retrieve the width from it. You can then calculate how much smaller or bigger the text should be to fit the size you want by calculating a scale factor:"""
size = 60
font = 'my-font.ttf'
while True:
counter += 1
ans = fit(500, 500, font, size, text)
if ans == True:
break
else:
size = ans
size -=1
print("Font_Size: {}".format(size))
print("Repetitions: {} ".format(counter))
第二个代码可以正常工作,但并不像预期的那样:只需要 2 重复就可以得出完美的字体大小 34 (我们已经知道它实际上是 45 )。但显然,第二个代码考虑到scale
因子运行得更快。
我的问题是:错误在哪里?或者这是我们使用这种方法得到的最佳近似值?你还有其他想法来解决这个问题吗?
我不想一次完美的字体大小,我想要的是减少重复。