Skip to main content
 首页 » 编程设计

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

2024年11月24日10wuhuacong

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

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

请您参考如下方法:

如果图像是“ 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_MULT 将 image 与 maskImage 混合:

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 :