Rendering text with multiple lines in pygame

后端 未结 9 1597
日久生厌
日久生厌 2020-11-29 12:15

I am trying to make a game and I am trying to render a lot of text. When the text renders, the rest of the text goes off the screen. Is there any easy way to make the text g

9条回答
  •  佛祖请我去吃肉
    2020-11-29 12:51

    Building on previous answers I made a somewhat comprehensive blit text function I can use with a single short command:

    def blittext(text, **kwargs):
        #blit text into screen, uses defaults and works for multiline strings
        fontface = kwargs.get('font', 'PressStart2P-Regular.ttf')
        b = kwargs.get('bold', False)
        fontsize = kwargs.get('size', 30)
        color = kwargs.get('color', (255, 255, 255))
        topleft = kwargs.get('topleft',(w/2,h/2))
        center = kwargs.get('center')
        textsurf = kwargs.get('surface',surface)
        maxwidth = kwargs.get('width',w)
        try:
            myfont = pygame.font.Font('/storage/emulated/0/games/' + fontface, fontsize)
        except:
            myfont = pygame.font.SysFont(fontface, fontsize, bold=b)
        x,y = topleft
        charwidth = myfont.size(' ')[0]
        charheight = fontsize + 3
        
        if center:
            for l in text.splitlines():
                mytext = myfont.render(l, False, color)
                textrect = mytext.get_rect(center=center)
                center = (center[0],center[1]+charheight)
                textsurf.blit(mytext,textrect)      
        else:
            for line in text.splitlines():
                for word in line.split(' '):
                    mytext = myfont.render(word, False, color)
                    textrect = mytext.get_rect(topleft=(x,y))
                    wordwidth = textrect.width
                    if x + wordwidth >= maxwidth:
                        x,y = (topleft[0], y + charheight)
                    textsurf.blit(mytext,(x,y))
                    x += charwidth + wordwidth
                x,y = (topleft[0], y + charheight)
    

提交回复
热议问题