Skip to main content

TextWrap — wiki

Simple Text Wrapping for pygame.

Simple function that will draw text and wrap it to fit the rect passed.  If there is any text that will not fit into the box, the remaining text will be returned.

lineSpacing can be adjusted for the font you are using. Negative values will make the line closer together.

WARNING! When copy/pasting this code, you will need to change "&lt;" to the < symbol and "&gt;" to the > symbol. Additionally, you may need to change Rect to pygame.Rect in line 5.

<bitcraft>

# draw some text into an area of a surface
# automatically wraps words
# returns any text that didn't get blitted
def drawText(surface, text, color, rect, font, aa=False, bkg=None):
    rect = Rect(rect)
    y = rect.top
    lineSpacing = -2

    # get the height of the font
    fontHeight = font.size("Tg")[1]

    while text:
        i = 1

        # determine if the row of text will be outside our area
        if y + fontHeight &gt; rect.bottom:
            break

        # determine maximum width of line
        while font.size(text[:i])[0] &lt; rect.width and i &lt; len(text):
            i += 1

        # if we've wrapped the text, then adjust the wrap to the last word      
        if i &lt; len(text): 
            i = text.rfind(" ", 0, i) + 1

        # render the line and blit it to the surface
        if bkg:
            image = font.render(text[:i], 1, color, bkg)
            image.set_colorkey(bkg)
        else:
            image = font.render(text[:i], aa, color)

        surface.blit(image, (rect.left, y))
        y += fontHeight + lineSpacing

        # remove the text we just blitted
        text = text[i:]

    return text