如何在Pygame中更改图像的颜色?

时间:2018-12-23 15:19:29

标签: python colors pygame transform

如何在Pygame中更改图像的颜色? 我有一个蓝色的六角形png文件,有什么简单的方法可以加载它并将其更改为红色或其他颜色?

1 个答案:

答案 0 :(得分:1)

如果要用单色填充整个图像但要保留透明度,则可以利用两个嵌套的for循环和pygame.Surface.set_at方法来更改表面的每个像素。

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
img = pg.Surface((150, 150), pg.SRCALPHA)
pg.draw.polygon(img, (0, 100, 200), ((75, 0), (150, 75), (75, 150), (0, 75)))

def set_color(img, color):
    for x in range(img.get_width()):
        for y in range(img.get_height()):
            color.a = img.get_at((x, y)).a  # Preserve the alpha value.
            img.set_at((x, y), color)  # Set the color of the pixel.

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_j:
                set_color(img, pg.Color(255, 0, 0))
            elif event.key == pg.K_h:
                set_color(img, pg.Color(0, 100, 200))

    screen.fill(BG_COLOR)
    screen.blit(img, (200, 200))
    pg.display.flip()
    clock.tick(60)

如果要着色表面,请看一下这篇文章:https://stackoverflow.com/a/49017847/6220679

相关问题