如何在 Pygame 中更改图像的颜色而不改变其透明度?

Joh*_*n_F 6 python pygame

这听起来像是一件简单的事情,但我却很挣扎。我有一个矩形的 png 图像,其透明中心称为“零”。我想改变图像可见部分的颜色。为了尝试改变它,我尝试使用“zero.fill”,但没有选择我尝试仅更改不透明部分,或者它将新颜色与旧颜色合并并保持原样。我不热衷于安装 numpy,因为我希望将完成的程序带给没有它的朋友。欢迎任何简单的建议。

skr*_*krx 6

我有一个适用于每像素 alpha 表面的示例,该表面也可以是半透明的。该fill函数只是循环表面的像素并将它们设置为新颜色,但保留它们的 alpha 值。可能不建议对具有多个表面的每个帧都执行此操作。(按 f、g、h 更改颜色。)

import sys
import pygame as pg


def fill(surface, color):
    """Fill all pixels of the surface with color, preserve transparency."""
    w, h = surface.get_size()
    r, g, b, _ = color
    for x in range(w):
        for y in range(h):
            a = surface.get_at((x, y))[3]
            surface.set_at((x, y), pg.Color(r, g, b, a))


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()

    # Uncomment this for a non-translucent surface.
    # surface = pg.Surface((100, 150), pg.SRCALPHA)
    # pg.draw.circle(surface, pg.Color(40, 240, 120), (50, 50), 50)
    surface = pg.image.load('bullet2.png').convert_alpha()
    surface = pg.transform.rotozoom(surface, 0, 2)

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_f:
                    fill(surface, pg.Color(240, 200, 40))
                if event.key == pg.K_g:
                    fill(surface, pg.Color(250, 10, 40))
                if event.key == pg.K_h:
                    fill(surface, pg.Color(40, 240, 120))

        screen.fill(pg.Color('lightskyblue4'))
        pg.draw.rect(screen, pg.Color(40, 50, 50), (210, 210, 50, 90))
        screen.blit(surface, (200, 200))

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()
Run Code Online (Sandbox Code Playgroud)

子弹2.png