pygame is
Python
Simple DirectMedia Layer
 
 
pygame.org is
Site Swing
Wiki

TextWrapping

      
Search:  
 
 

This snippet of code will convert a string of text into a list containing the lines it would break down into for a certain font and width.

from itertools import chain
 
def truncline(text, font, maxwidth):
        real=len(text)       
        stext=text           
        l=font.size(text)[0]
        cut=0
        a=0                  
        done=1
        old = None
        while l > maxwidth:
            a=a+1
            n=text.rsplit(None, a)[0]
            if stext == n:
                cut += 1
                stext= n[:-cut]
            else:
                stext = n
            l=font.size(stext)[0]
            real=len(stext)               
            done=0                        
        return real, done, stext             
        
def wrapline(text, font, maxwidth): 
    done=0                      
    wrapped=[]                  
                               
    while not done:             
        nl, done, stext=truncline(text, font, maxwidth) 
        wrapped.append(stext.strip())                  
        text=text[nl:]                                 
    return wrapped
 
 
def wrap_multi_line(text, font, maxwidth):
    """ returns text taking new lines into account.
    """
    lines = chain(*(wrapline(line, font, maxwidth) for line in text.splitlines()))
    return list(lines)

So:

pygame.init() 
font=pygame.font.Font(None, 17)
print wrapline("Now is the time for all good men to come to the aid of their country", font, 120)
outputs: ['Now is the time for all', 'good men to come to', 'the aid of their', 'country']

Now actually displaying that text (which you will have to do line by line) is another matter.
But it was easier for me to display the text than to write this code to wrap a line, it really stumped me for a while.

(Update: An obnoxiously long word that rsplit can't break up would previously cause an infinite loop. Added a cutoff to start splitting the word once 'stext' stops changing). What this means from the point of view ? Is necessary to make modifications ?



page migrated to new wiki
spotlight

 
our projects
pygame.org welcomes all python game, art, music, sound, video and multimedia projects. If they use pygame or not.
 
recent releases
Apr 25, 2014

Apr 21, 2014


Apr 19, 2014

Apr 16, 2014

Apr 13, 2014

Apr 9, 2014

Mar 18, 2014


Mar 15, 2014

Mar 14, 2014

Mar 13, 2014

... more!
 
for pygame related questions, comments, and suggestions, please see help (lists, irc)