Skip to content

Instantly share code, notes, and snippets.

@omirete
Forked from Eyongkevin/text_wrap.py
Last active February 7, 2020 01:31
Show Gist options
  • Save omirete/90ab4694e23c88f3a61e0b5d70934e44 to your computer and use it in GitHub Desktop.
Save omirete/90ab4694e23c88f3a61e0b5d70934e44 to your computer and use it in GitHub Desktop.
Function to split text into list of sentences where none exceeds a given maximum width, based on the font size.
from PIL import ImageFont
def get_wrapped_text(text, PIL_font, max_width):
# Returns a list where each item is a line of text that does not exceed
# the max_width. If there should be any single word that is bigger than
# the max_width argument, it will be shown in an individual line, even
# though it exceeds the max_width.
lines = []
# Split the line by spaces to get a list of words.
words = text.split(' ')
# Append every word to a line while its width is shorter than the image
# width
i = 0
while i < len(words):
line = ''
while i < len(words):
new_line = line + ' ' + words[i]
if PIL_font.getsize(new_line)[0] <= max_width:
line = new_line
i += 1
else:
break
if line == '':
line = words[i]
i += 1
else:
line = line[1:] # This is to remove the initial space character
# introduced in line 23.
lines.append(line)
return lines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment