将screen.fill设置为pygame中的渐变?

时间:2018-08-27 18:54:59

标签: python background pygame gradient background-color

我正在尝试将背景设置为从黑色到红色的渐变(过渡是垂直的,顶部是黑色,底部是红色)。我怎样才能达到这种效果?

1 个答案:

答案 0 :(得分:1)

有一个不错的模块,由DR0ID称为gradients.py

这是使用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函数,允许您为每个颜色通道传递不同的功能。