Fix too long lines in height fitted text
This commit is contained in:
parent
4bdb89ae60
commit
78afd0549c
1 changed files with 9 additions and 2 deletions
11
app.py
11
app.py
|
|
@ -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)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue