python - Perfect font size to fit in specific width and height -
what wanted function given image width
, height
, text
fit text image perfect font size. achieved trial-error method. here's code:
# -*- coding: utf-8 -*- 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 pass text default font size of, 20, imagettfbbox , retrieve width it. can calculate how smaller or bigger text should fit size want calculating 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))
in specific example (from code above) takes 16 repetitions , perfect font size 45. now, investigating little in stackoverflow found questions regarding same problem , 1 solutions called attention: https://stackoverflow.com/a/10689312/5106998
so modified code follows:
# -*- coding: utf-8 -*- 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 pass text default font size of, 20, imagettfbbox , retrieve width it. can calculate how smaller or bigger text should fit size want calculating 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))
the second code works not expected: takes 2 repetitions conclude perfect font size 34 (we know 45). second code, taking consideration scale
factor runs lot faster.
my question is: mistake? or best approximation can using method? have other ideas tackle down problem?
i don't want perfect font size @ once, want reduce repetitions.
Comments
Post a Comment