Rendering text with multiple lines in pygame

后端 未结 9 1575
日久生厌
日久生厌 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:49

    There is no easy way to render text on multiple lines in pygame, but this helper function could provide some use to you. Just pass in your text (with newlines), x, y, and font size.

    def render_multi_line(text, x, y, fsize)
            lines = text.splitlines()
            for i, l in enumerate(lines):
                screen.blit(sys_font.render(l, 0, hecolor), (x, y + fsize*i))
    
    0 讨论(0)
  • 2020-11-29 12:51

    One thing you could do is use a monospaced font. They have the same size for all characters and so are beloved by programmers. That's going to be my solution for handling the height/width problem.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题