When playing around with opacity in pygame, I noticed that when you neglect to fill the primary Surface created by pygame.display.set_mode()
with a color. You can create a pretty neat color fade-in effect by blitting another Surface on top of it. Oddly, it seems this affect is controlled by the value of alpha and the tick rate of pygame.time.Clock()
If the value of alpha is >= the tick rate, the effect is instant, and when the value of alpha is < the tick rate, the speed of the effect seems to lengthen as the difference between tick rate - alpha
increases. I currently have no idea why this is the case, so I'm hoping someone more experienced with the library can provide insight into the cause of the effect.
import pygame
def main():
button_rect = pygame.Rect(0, 0, 200, 40)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
# When the window is not filled with a color you get a cool
# fade-in effect.
# window.fill((0, 0, 0))
container = pygame.Surface((848, 480), pygame.SRCALPHA)
container.fill((30, 30, 30))
# Place button in center of screen.
button_rect.center = window.get_rect().center
mouse_pos = pygame.mouse.get_pos()
# The value of alpha affects the speed of the effect
alpha = 10
if button_rect.collidepoint(mouse_pos):
button = pygame.draw.rect(container,
(255, 0, 0, alpha),
button_rect)
else:
button = pygame.draw.rect(container,
(255, 255, 255, alpha),
button_rect)
window.blit(container, (0, 0))
window.blit(text, text.get_rect(center=button.center))
pygame.display.update(container.get_rect())
# Clock speed affects fade-in time as well.
clock.tick(60)
if __name__ == "__main__":
initalized, unintialized = pygame.init()
window = pygame.display.set_mode((848, 480), pygame.RESIZABLE)
clock = pygame.time.Clock()
font = pygame.font.Font("../assets/fonts/terminal.ttf", 20)
text = font.render("Hello", 0, (0,0,0))
main()
CodePudding user response:
You draw a transparent surface over the window surface in each frame. This creates a fade in effect. The drawing in the window becomes more and more solid the more often you put the transparent surface over it. Increasing the tick rate and doing it more often will make the fade in faster. Increasing the alpha value makes the Surface you're laying over the window less transparent, and the fad-in becomes faster as well.
See also How to fade in a text or an image with PyGame.