Python Pillow Multi-color text

I found the answer to my question, and because there are no responses online I’m posting my own answer for those who might stumble across:

You calculate the length of the previous snippet of text, then add it to the starting x value, then until you are out of text continue doing that.

def gen_name(draw, stars, rank, name, color):
    # stats.rank_color = {
    #     'bracket_color': (231, 79, 80),
    #     'rank_color': (255, 255, 255),
    #     'plus_color': None
    # }
    font = 'fonts/Minecraftia-Regular.ttf'
    size = 50
    f = ImageFont.truetype(font=font, size=size)
    t = f'[{stars}]'
    x = 20
    y = 20
    _text(draw, x, y, t, size, (180, 180, 180), background=False, font=font)
    x = x + draw.textsize(t, font=f)[0]
    if rank != 'MEMBER':
        t = '['
        _text(draw, x, y, t, size, color['bracket_color'], background=False, font=font)
        x = x + draw.textsize(t, font=f)[0]
        t = rank[:rank.index('+')]
        _text(draw, x, y, t, size, color['rank_color'], background=False, font=font)
        x = x + draw.textsize(t, font=f)[0]
        if '+' in rank:
            t = rank[rank.index('+'):]
            _text(draw, x, y, t, size, color['plus_color'], background=False, font=font)
            x = x + draw.textsize(t, font=f)[0]
            t = ']'
            _text(draw, x, y, t, size, color['bracket_color'], background=False, font=font)
            x = x + draw.textsize(t, font=f)[0]
            t = name
            _text(draw, x, y, t, size, color['bracket_color'], background=False, font=font)
            x = x + draw.textsize(t, font=f)[0]
        else:
            t = ']'
            _text(draw, x, y, t, size, color['bracket_color'], background=False, font=font)
            x = x + draw.textsize(t, font=f)[0]
            t = name
            _text(draw, x, y, t, size, color['bracket_color'], background=False, font=font)
            x = x + draw.textsize(t, font=f)[0]
    else:
        t = name
        _text(draw, x, y, t, size, color['rank_color'], background=False, font=font)
        x = x + draw.textsize(t, font=f)[0]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top