我正在尝试将背景设置为从黑色到红色的渐变(其中过渡是垂直的/顶部是黑色,底部是红色)。怎样才能达到这样的效果呢?
最佳答案
有一个不错的模块,名为 gradients.py通过 DR0ID。
这是更简单的垂直梯度函数,它使用 linear interpolation :
def vertical(size, startcolor, endcolor):
"""
Draws a vertical linear gradient filling the entire surface. Returns a
surface filled with the gradient (numeric is only 2-3 times faster).
"""
height = size[1]
bigSurf = pygame.Surface((1,height)).convert_alpha()
dd = 1.0/height
sr, sg, sb, sa = startcolor
er, eg, eb, ea = endcolor
rm = (er-sr)*dd
gm = (eg-sg)*dd
bm = (eb-sb)*dd
am = (ea-sa)*dd
for y in range(height):
bigSurf.set_at((0,y),
(int(sr + rm*y),
int(sg + gm*y),
int(sb + bm*y),
int(sa + am*y))
)
return pygame.transform.scale(bigSurf, size)
还有一个更通用的 vertical_func
函数,它允许您为每个颜色 channel 传递不同的函数。
关于python - 在pygame中将screen.fill设置为渐变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52045413/