Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

pygame text wrapping

def renderTextCenteredAt(text, font, colour, x, y, screen, allowed_width):
    # first, split the text into words
    words = text.split()

    # now, construct lines out of these words
    lines = []
    while len(words) > 0:
        # get as many words as will fit within allowed_width
        line_words = []
        while len(words) > 0:
            line_words.append(words.pop(0))
            fw, fh = font.size(' '.join(line_words + words[:1]))
            if fw > allowed_width:
                break

        # add a line consisting of those words
        line = ' '.join(line_words)
        lines.append(line)

    # now we've split our text into lines that fit into the width, actually
    # render them

    # we'll render each line below the last, so we need to keep track of
    # the culmative height of the lines we've rendered so far
    y_offset = 0
    for line in lines:
        fw, fh = font.size(line)

        # (tx, ty) is the top-left of the font surface
        tx = x - fw / 2
        ty = y + y_offset

        font_surface = font.render(line, True, colour)
        screen.blit(font_surface, (tx, ty))

        y_offset += fh
Comment

PREVIOUS NEXT
Code Example
Python :: import turtle as t 
Python :: pillow image from array 
Python :: glob python 
Python :: neural network hyperparameter tuning 
Python :: max of double array python 
Python :: python array looping 
Python :: a string starts with an uppercase python 
Python :: pandas where retuning NaN 
Python :: sentence similarity python 
Python :: pil resize image 
Python :: python get column from grouped dataframe 
Python :: convert negative to positive in python 
Python :: TypeError: Can only append a dict if ignore_index=True 
Python :: tkinter responsive gui 
Python :: install json on python 
Python :: dm user discord.py 
Python :: fastapi upload file save 
Python :: python add attribute to class instance 
Python :: tkinter treeview clear 
Python :: append to set python 
Python :: change key of dictionary python 
Python :: python append list 
Python :: python string to list new line 
Python :: python get 1st arg 
Python :: how to create a virtual environment in python 
Python :: python dict sortieren 
Python :: python send sigint to subprocess 
Python :: how to host python flask web application 
Python :: RuntimeError: dictionary changed size during iteration 
Python :: seaborrn set figsize 
ADD CONTENT
Topic
Content
Source link
Name
5+3 =