Search code examples
pythontextpygameopacityfade

How to fade in and out a text in Pygame


I know how to show a text on screen, but I don't like the way it appears and disappears. I want it to fade in and out. Changing the RGB is impossible because there is a background image. Can you tell me a code which changes the text's opacity?


Solution

  • To fade out the text, you can blit a white, transparent surface onto the text surface and pass the pygame.BLEND_RGBA_MULT special flag.

    Reduce (or increase to fade-in) the alpha value each frame or after a specific time interval (check out these timers) and use it to fill the alpha_surf:

    alpha = max(alpha-4, 0)
    alpha_surf.fill((255, 255, 255, alpha))
    

    Also, create a copy of the original text surface each time you change the alpha, otherwise it would fade-out too quickly because the original gets modified. Here's a minimal, complete example:

    import pygame as pg
    
    
    def main():
        clock = pg.time.Clock()
        screen = pg.display.set_mode((640, 480))
        font = pg.font.Font(None, 64)
        blue = pg.Color('royalblue')
        orig_surf = font.render('Enter your text', True, blue)
        txt_surf = orig_surf.copy()
        # This surface is used to adjust the alpha of the txt_surf.
        alpha_surf = pg.Surface(txt_surf.get_size(), pg.SRCALPHA)
        alpha = 255  # The current alpha value of the surface.
    
        while True:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    return
    
            if alpha > 0:
                # Reduce alpha each frame, but make sure it doesn't get below 0.
                alpha = max(alpha-4, 0)
                txt_surf = orig_surf.copy()  # Don't modify the original text surf.
                # Fill alpha_surf with this color to set its alpha value.
                alpha_surf.fill((255, 255, 255, alpha))
                # To make the text surface transparent, blit the transparent
                # alpha_surf onto it with the BLEND_RGBA_MULT flag.
                txt_surf.blit(alpha_surf, (0, 0), special_flags=pg.BLEND_RGBA_MULT)
    
            screen.fill((30, 30, 30))
            screen.blit(txt_surf, (30, 60))
            pg.display.flip()
            clock.tick(30)
    
    
    if __name__ == '__main__':
        pg.init()
        main()
        pg.quit()