-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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