Fix too long lines in height fitted text

This commit is contained in:
Tobias Reisinger 2026-02-16 00:02:33 +01:00
parent 4bdb89ae60
commit 78afd0549c
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE

11
app.py
View file

@ -9,12 +9,15 @@ default_font = "atkinson-hyperlegible.ttf"
def get_wrapped_text(text: str, font: ImageFont.ImageFont, line_length: int):
lines = ['']
for word in text.split():
if font.getlength(word) > line_length:
return None
line = f'{lines[-1]} {word}'.strip()
if font.getlength(line) <= line_length:
lines[-1] = line
else:
lines.append(word)
return '\n'.join(lines)
return ('\n'.join(lines)).strip('\n')
def draw_fitted_text_h(draw, pos, text: str, font_size: int, max_width: int, max_height: int):
bbox_h = float("inf")
@ -25,7 +28,11 @@ def draw_fitted_text_h(draw, pos, text: str, font_size: int, max_width: int, max
font = font.font_variant(size=font_size)
font_size -= 1
text_wrapped = get_wrapped_text(text, font, line_length=max_width).strip('\n')
text_wrapped = get_wrapped_text(text, font, line_length=max_width)
if text_wrapped == None:
continue
bbox_h = draw.textbbox((0, 0), text_wrapped, font=font)[3]
draw.text(pos, text_wrapped, 0, font=font)