[英]Python 3 and bisection functions to check size of a font
我具有以下功能来检查font size
是否足够小以适合尺寸为x
, y
的image
。
from PIL import ImageFont
def fit(width, height, font, size, text):
font = ImageFont.truetype(font, size)
text_w, text_h = font.getsize(text)
text_area = text_w*text_h
total_area = width*height
if total_area>text_area:
return True
else:
return False
font = 'font.ttf'
counter = 0
size = 60
text = """
The module is called bisect because it uses a basic bisection algorithm to do its w
"""
while True:
counter += 1
ans = fit(500, 500, font, size, text)
if ans == True:
break
else:
size -=1
print("Font_Size: {}".format(size))
print("Repetitions: {} ".format(counter))
好的,这些代码将图像的width
和height
作为参数,并计算总面积,并与文本的总面积进行比较,如果合适( total area > total area text
),则返回true。 我想做的是以下几点:
我想要适合该区域的最大font size
。
我们可以使用for循环来实现这一点,该循环从一个高值开始并在每次迭代中减去1
。 可以,但是很慢。
我想知道是否有任何方法可以使用Python实现的二等分算法的内置函数来实现这一目标,或者您还有其他想法吗?
我使用的字体如下: https : //www.google.com/fonts#QuickUsePlace : quickUse/Family : Open+Sans
上面的代码的输出是: Font_Size: 49 Repetitions: 12
给定两个整数a<b
和一个单调函数f
从整数到布尔值( True,False
),其中f(a) = True
和f(b) = False
可以找到最大整数m
在[a,b[
与f(m) = True
具有以下函数:
def findMaxOk(low_ok, high_notOk, f):
print "find max. ok in [%d,%d[" % (low_ok, high_notOk)
if low_ok+1 >= high_notOk:
return low_ok
mid = (low_ok + high_notOk) // 2
if f(mid):
return findMaxOk(mid, high_notOk, f)
else:
return findMaxOk(low_ok, mid, f)
要找到最大字体大小,您可以定义如下函数:
def maxFittingFontSize(width, height, font, text):
f = lambda size: fit(width, height, font, size, text)
return findMaxOk(1, 100, f)
顺便说一句:您是否不想分别比较您的功能fit
宽度和高度? 喜欢:
def fit(width, height, font, size, text):
font = ImageFont.truetype(font, size)
text_w, text_h = font.getsize(text)
return text_w<width and text_h<height
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.