【问题标题】:Is it possible to change sprite colours in Pygame?是否可以在 Pygame 中更改精灵颜色?
【发布时间】:2019-05-19 16:09:09
【问题描述】:

我正在使用 Pygame 用 Python 制作一个游戏,它在游戏开始之前包含一个小型头像制作器,但是我没有创建一个包含 88 种不同发型和颜色组合的大型精灵表,有没有一种方法可以让我使用每个发型的通用 .png 图像并在游戏中为其应用颜色?

发型保存为带有 alpha 和抗锯齿的 .png 图像,因此它们不仅仅是一种颜色。我有 8 种不同的发型和 11 种不同的颜色。将它们作为精灵表加载并在游戏中剪辑它们不是问题,但如果有一种方法可以在游戏中应用颜色(或色调),那么不仅在内存上会更容易,而且会打开更多的可能性。

【问题讨论】:

    标签: python python-3.x colors pygame sprite


    【解决方案1】:

    如果图像是“蒙版”图像,具有透明背景和白色(255、255、255)蒙版,那么您可以轻松“着色”图像。

    加载图片:

    image = pygame.image.load(imageName)
    

    生成具有 alpha 通道且大小相同的统一彩色图像:

    colorImage = pygame.Surface(image.get_size()).convert_alpha()
    colorImage.fill(color)
    

    使用过滤器BLEND_RGBA_MULTimagemaskImage 混合:

    image.blit(colorImage, (0,0), special_flags = pygame.BLEND_RGBA_MULT)
    

    精灵类可能如下所示:

    class MySprite(pygame.sprite.Sprite):
    
        def __init__(self, imageName, color):
            super().__init__() 
    
            self.image = pygame.image.load(imageName)
            self.rect = self.image.get_rect()
                    
            colorImage = pygame.Surface(self.image.get_size()).convert_alpha()
            colorImage.fill(color)
            self.image.blit(colorImage, (0,0), special_flags = pygame.BLEND_RGBA_MULT)
    

    最小示例: repl.it/@Rabbid76/PyGame-ChangeColorOfSurfaceArea-4

    import pygame
    
    def changColor(image, color):
        colouredImage = pygame.Surface(image.get_size())
        colouredImage.fill(color)
        
        finalImage = image.copy()
        finalImage.blit(colouredImage, (0, 0), special_flags = pygame.BLEND_MULT)
        return finalImage
    
    pygame.init()
    window = pygame.display.set_mode((300, 160))
    
    image = pygame.image.load('CarWhiteDragon256.png').convert_alpha()
    hue = 0
    
    clock = pygame.time.Clock()
    nextColorTime = 0
    run = True
    while run:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
    
        color = pygame.Color(0)
        color.hsla = (hue, 100, 50, 100)
        hue = hue + 1 if hue < 360 else 0 
    
        color_image = changColor(image, color)
    
        window.fill((96, 96, 64))
        window.blit(color_image, color_image.get_rect(center = window.get_rect().center))
        pygame.display.flip()
    
    pygame.quit()
    exit()
    

    精灵:

    【讨论】:

    • 谢谢@Rabbid76,效果很好!我的蒙版图像已经有透明背景,我将图像的默认颜色更改为白色,并根据您的建议,在游戏中更改了它的颜色。这意味着我现在可以使用无限的颜色,只需将默认部分导入游戏。很好的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    相关资源
    最近更新 更多