python – 如何在pygame中从一种颜色淡化到另一种颜色?
发布时间:2020-12-20 12:14:32 所属栏目:Python 来源:网络整理
导读:如何在pygame中从一种颜色淡入另一种颜色?我想慢慢地将圆圈的颜色从绿色变为蓝色,紫色变为粉红色,红色变为橙色,黄色变为绿色.我该怎么办?目前,我正在使用 def colour(): switcher = { 0: 0x2FD596,1: 0x2FC3D5,2: 0x2F6BD5,3: 0x432FD5,4: 0x702FD5,5: 0xB
如何在pygame中从一种颜色淡入另一种颜色?我想慢慢地将圆圈的颜色从绿色变为蓝色,紫色变为粉红色,红色变为橙色,黄色变为绿色.我该怎么办?目前,我正在使用
def colour(): switcher = { 0: 0x2FD596,1: 0x2FC3D5,2: 0x2F6BD5,3: 0x432FD5,4: 0x702FD5,5: 0xBC2FD5,6: 0xD52F91,7: 0xD52F43,8: 0xD57F2F,9: 0xD5D52F,10: 0x64D52F,11: 0x2FD557,} return switcher.get(round((datetime.datetime.now() - starting_time).total_seconds()%11)) 但这在颜色和看起来笨重之间有很大的进步. 解决方法
关键是要简单计算每一步改变每个通道(a,r,g和b)的程度. Pygame的Color类非常方便,因为它允许在每个通道上进行迭代,并且它的输入很灵活,所以你可以改变它.在下面的例子中,’blue’到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,pygame.color.Color(next_color))] else: ... ... pygame.display.update() step += clock.tick(60) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |