【问题标题】:How can I change an image's color in Pygame? [duplicate]如何在 Pygame 中更改图像的颜色? [复制]
【发布时间】:2019-05-23 02:33:47
【问题描述】:

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

【问题讨论】:

    标签: python colors pygame transform


    【解决方案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

    【讨论】:

    • 谢谢。虽然第一种方法不起作用,但第二种方法对我来说非常有效。
    猜你喜欢
    • 1970-01-01
    • 2017-05-02
    • 2023-03-20
    • 2012-08-22
    • 2014-01-13
    • 2011-08-19
    • 2018-11-25
    • 2018-10-24
    • 1970-01-01
    相关资源
    最近更新 更多