如何在 Pygame 中淡入淡出文本
How to fade in and out a text in Pygame
我知道如何在屏幕上显示文本,但我不喜欢它出现和消失的方式。我想让它淡入淡出。更改 RGB 是不可能的,因为有背景图像。你能告诉我一个改变文本不透明度的代码吗?
要使文本淡出,您可以将白色透明表面 blit 到文本表面并传递 pygame.BLEND_RGBA_MULT
特殊标志。
减少(或增加淡入)每帧或特定时间间隔后的 alpha 值(查看这些 )并使用它来填充 alpha_surf
:
alpha = max(alpha-4, 0)
alpha_surf.fill((255, 255, 255, alpha))
此外,每次更改 alpha 时都创建原始文本表面的副本,否则它会因为原始文本被修改而淡出得太快。这是一个最小的完整示例:
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()
我知道如何在屏幕上显示文本,但我不喜欢它出现和消失的方式。我想让它淡入淡出。更改 RGB 是不可能的,因为有背景图像。你能告诉我一个改变文本不透明度的代码吗?
要使文本淡出,您可以将白色透明表面 blit 到文本表面并传递 pygame.BLEND_RGBA_MULT
特殊标志。
减少(或增加淡入)每帧或特定时间间隔后的 alpha 值(查看这些 alpha_surf
:
alpha = max(alpha-4, 0)
alpha_surf.fill((255, 255, 255, alpha))
此外,每次更改 alpha 时都创建原始文本表面的副本,否则它会因为原始文本被修改而淡出得太快。这是一个最小的完整示例:
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()