python - 是否可以在 Pygame 中更改 Sprite 颜色?

标签 python python-3.x colors pygame sprite

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

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

hairstyles

最佳答案

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

加载图片:

image = pygame.image.load(imageName)

生成具有 alpha channel 且大小相同的均匀彩色图像:

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)

Sprite 类可能如下所示:

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()

Sprite :

关于python - 是否可以在 Pygame 中更改 Sprite 颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56209634/

相关文章:

python - 在Windows 7上用Python快速获取屏幕上某些像素点的颜色

python - Python中是否有相当于//运算符的上限?

python - 情节不会在 Jupyter 中显示

python - Pandas:根据复杂逻辑删除具有特定字符串的行和列

python - 使用 https 代理请求

java - 如何更改 JTable 中文本段落的颜色?

python - 纯 Python 逆误差函数

python - 尝试压缩一个句子然后将其上传到文件

python - 需要 py-upset 帮助吗?

c# - 编写一个简单的配色方案生成器