Created
December 14, 2019 12:29
-
-
Save Eyongkevin/adbac2334f1355d8045111c264d80621 to your computer and use it in GitHub Desktop.
Split text into line of sub-strings base on the font size and a given maximum width.
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
def text_wrap(text, font, max_width): | |
"""Wrap text base on specified width. | |
This is to enable text of width more than the image width to be display | |
nicely. | |
@params: | |
text: str | |
text to wrap | |
font: obj | |
font of the text | |
max_width: int | |
width to split the text with | |
@return | |
lines: list[str] | |
list of sub-strings | |
""" | |
lines = [] | |
# If the text width is smaller than the image width, then no need to split | |
# just add it to the line list and return | |
if font.getsize(text)[0] <= max_width: | |
lines.append(text) | |
else: | |
#split the line by spaces to get words | |
words = text.split(' ') | |
i = 0 | |
# append every word to a line while its width is shorter than the image width | |
while i < len(words): | |
line = '' | |
while i < len(words) and font.getsize(line + words[i])[0] <= max_width: | |
line = line + words[i]+ " " | |
i += 1 | |
if not line: | |
line = words[i] | |
i += 1 | |
lines.append(line) | |
return lines |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Eyong, Is this code snippet free to use? Is there a way to specify a license for this snippet?