Untitled

 avatar
unknown
python
a year ago
1.2 kB
8
Indexable
import json
from PIL import Image, ImageDraw, ImageFont

def getTextWidth(text):
    if not text:
        return 0

    font_name = 'SamsungOneUI-600.ttf'
    font_size = 15
    font = ImageFont.truetype(font_name, font_size)
    left, top, right, bottom = font.getbbox(text)
    return right - left

def splitStringIntoLines(text, width):
    lines = []
    while text:
        wordPoint = 0
        count = len(text.split())
        first = text
        rest = ''
        splitted = False
        while first:
            if getTextWidth(first) <= width:
                splitted = True
                break
            wordPoint += 1
            temp = first
            first = text.rsplit(None, wordPoint)[0]
            if first == temp:
                break
            rest = text.split(None, count - wordPoint)[-1]
        if not splitted:
            splitPoint = 0
            for i in reversed(range(len(text))):
                first = text[:i]
                rest = text[i:]
                if getTextWidth(first) <= width:
                    splitPoint = i
                    break
        text = rest
        lines.append(first)
    return lines
Editor is loading...
Leave a Comment