关键是简单地计算每一步需要改变每个通道(a、r、g 和 b)的量。 Pygame 的Color
类非常方便,因为它允许在每个通道上进行迭代,并且它的输入很灵活,因此您可以更改例如'blue'
to 0x2FD596
在下面的示例中,它仍然会运行。
这是一个简单的运行示例:
import pygame
import itertools
pygame.init()
screen = pygame.display.set_mode((800, 600))
colors = itertools.cycle(['green', 'blue', 'purple', 'pink', 'red', 'orange'])
clock = pygame.time.Clock()
base_color = next(colors)
next_color = next(colors)
current_color = base_color
FPS = 60
change_every_x_seconds = 3.
number_of_steps = change_every_x_seconds * FPS
step = 1
font = pygame.font.SysFont('Arial', 50)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
text = font.render('fading {a} to {b}'.format(a=base_color, b=next_color), True, pygame.color.Color('black'))
step += 1
if step < number_of_steps:
# (y-x)/number_of_steps calculates the amount of change per step required to
# fade one channel of the old color to the new color
# We multiply it with the current step counter
current_color = [x + (((y-x)/number_of_steps)*step) for x, y in zip(pygame.color.Color(base_color), pygame.color.Color(next_color))]
else:
step = 1
base_color = next_color
next_color = next(colors)
screen.fill(pygame.color.Color('white'))
pygame.draw.circle(screen, current_color, screen.get_rect().center, 100)
screen.blit(text, (230, 100))
pygame.display.update()
clock.tick(FPS)
如果您不想依赖帧速率而是使用基于时间的方法,您可以将代码更改为:
...
change_every_x_milliseconds = 3000.
step = 0
running = True
while running:
...
if step < change_every_x_milliseconds:
current_color = [x + (((y-x)/change_every_x_milliseconds)*step) for x, y in zip(pygame.color.Color(base_color), pygame.color.Color(next_color))]
else:
...
...
pygame.display.update()
step += clock.tick(60)