Skip to content

Commit cccc072

Browse files
committed
Do not justify a single word
1 parent 3d41195 commit cccc072

File tree

3 files changed

+31
-17
lines changed

3 files changed

+31
-17
lines changed
2.38 KB
Loading

Tests/test_imagefont.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,18 @@ def test_render_multiline_text_align(
267267
assert_image_similar_tofile(im, f"Tests/images/multiline_text{ext}.png", 0.01)
268268

269269

270+
def test_render_multiline_text_align_justify_single_word(
271+
font: ImageFont.FreeTypeFont,
272+
) -> None:
273+
im = Image.new("RGB", (185, 65))
274+
draw = ImageDraw.Draw(im)
275+
draw.multiline_text(
276+
(0, 0), "hey you\nyou are awesome\nthis", font=font, align="justify"
277+
)
278+
279+
assert_image_equal_tofile(im, "Tests/images/multiline_text_justify_single_word.png")
280+
281+
270282
def test_unknown_align(font: ImageFont.FreeTypeFont) -> None:
271283
im = Image.new(mode="RGB", size=(300, 100))
272284
draw = ImageDraw.Draw(im)

src/PIL/ImageDraw.py

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -772,24 +772,26 @@ def _prepare_multiline_text(
772772

773773
if align == "justify" and width_difference != 0:
774774
words = line.split(" " if isinstance(text, str) else b" ")
775-
word_widths = [
776-
self.textlength(
777-
word,
778-
font,
779-
direction=direction,
780-
features=features,
781-
language=language,
782-
embedded_color=embedded_color,
783-
)
784-
for word in words
785-
]
786-
width_difference = max_width - sum(word_widths)
787-
for i, word in enumerate(words):
788-
parts.append(((left, top), word))
789-
left += word_widths[i] + width_difference / (len(words) - 1)
790-
else:
791-
parts.append(((left, top), line))
775+
if len(words) > 1:
776+
word_widths = [
777+
self.textlength(
778+
word,
779+
font,
780+
direction=direction,
781+
features=features,
782+
language=language,
783+
embedded_color=embedded_color,
784+
)
785+
for word in words
786+
]
787+
width_difference = max_width - sum(word_widths)
788+
for i, word in enumerate(words):
789+
parts.append(((left, top), word))
790+
left += word_widths[i] + width_difference / (len(words) - 1)
791+
top += line_spacing
792+
continue
792793

794+
parts.append(((left, top), line))
793795
top += line_spacing
794796

795797
return font, anchor, parts

0 commit comments

Comments
 (0)