pythonpygamepython-3.7pygame-surface

How to fade in a text or an image with PyGame


Can someone please help me?

I tried to make some text appear smoothly on the screen.:

def image(name, x, y, u):
   screen.blit(name,(x, y))
   if u == 1
      pygame.display.update()

windows = 'main'
while windows == 'main':
   image(background, 0, 0)
   image(title, 640, 120)

   pygame.display.update()

But text appears very suddenly and not the way I'd expected.


Solution

  • You want to use transparency, and pygame uses three different types:

    There are three types of transparency supported in pygame: colorkeys, surface alphas, and pixel alphas. Surface alphas can be mixed with colorkeys, but an image with per pixel alphas cannot use the other modes. Colorkey transparency makes a single color value transparent. Any pixels matching the colorkey will not be drawn. The surface alpha value is a single value that changes the transparency for the entire image. A surface alpha of 255 is opaque, and a value of 0 is completely transparent.

    Per pixel alphas are different because they store a transparency value for every pixel. This allows for the most precise transparency effects, but it also the slowest. Per pixel alphas cannot be mixed with surface alpha and colorkeys.

    So let's use colorkey to create a transparent Surface and blit some text to it, and then use surface alpha to create the fade in effect by calling set_alpha and the Surface:

    import pygame
    
    def main():
        screen = pygame.display.set_mode((300, 100))
        FONT = pygame.font.SysFont(None, 64)
        text = FONT.render('Hello World', False, pygame.Color('darkorange'))
        surf = pygame.Surface(text.get_rect().size)
        surf.set_colorkey((1,1,1))
        surf.fill((1,1,1))
        surf.blit(text, (0, 0))
        clock = pygame.time.Clock()
        alpha = 0
        while True:
            for e in pygame.event.get():
                if e.type == pygame.QUIT:
                    return
    
            alpha = (alpha + 1) % 256
            surf.set_alpha(alpha)
            
            screen.fill(pygame.Color('dodgerblue'))
            screen.blit(surf, (20, 20))
            clock.tick(120)
            print(alpha)
            pygame.display.update()
    
    if __name__ == '__main__':
        pygame.init()
        main()
    

    enter image description here