我的图片中的 alpha 通道问题PyGame

问题描述

目前,我正在尝试将图片粘贴到我的 pygame 游戏中,并且这张图片一个 alpha 通道(正如您在这句话下面看到的那样)。

Original Picture

但是,由于某种原因,当我使用 convert()convert_alpha() 时,它没有将带有 alpha 通道的图片正确放置在游戏中...即使我尝试对图片,没什么。

What happened (with the manipulations)

这是我尝试编写的代码(对 alpha 通道的操作无效):

class Spritesheet:
    # utility class for loading and parsing spritesheets
    def __init__(self,filename):
        self.spritesheet = pygame.image.load(filename).convert()

    def get_image(self,x,y,width,height):
        # grab an image out of a larger spritesheet
        image = pygame.Surface((width,height))
        image.fill(pygame.color.Color("black"))
        image.blit(self.spritesheet,(0,0),(x,height))
        image.set_colorkey(pygame.color.Color("black"))
        return image

如何将原本带有 Alpha 通道的图片放上去?

解决方法

确保图像具有透明度信息。如果背景不是透明的,你不能神奇地得到它(除非背景有统一的颜色)。见Pygame image transparency confusion


您必须使用 convert_alpha 而不是 convert

self.spritesheet = pygame.image.load(filename).convert()

self.spritesheet = pygame.image.load(filename).convert_alpha()

使用 convert_alpha() 使用提供每像素 alpha 的图像格式创建 Surface 的副本。使用 convert 时,图像的 Alpha 通道和透明度会丢失。

另外创建一个具有每像素 Alpha 格式的表面。设置 SRCALPHA 标志以使用包含每像素 alpha 的图像格式创建表面:

image = pygame.Surface((width,height))

image = pygame.Surface((width,height),pygame.SRCALPHA)
class Spritesheet:
    # utility class for loading and parsing spritesheets
    def __init__(self,filename):
        self.spritesheet = pygame.image.load(filename).convert_alpha()

    def get_image(self,x,y,width,height):
        # grab an image out of a larger spritesheet
        image = pygame.Surface((width,pygame.SRCALPHA)
        image.fill(pygame.color.Color("black"))
        image.blit(self.spritesheet,(0,0),(x,height))
        return image

或者,您可以使用 pygame.Surface.subsurface 创建子表面。见How can I crop an image with Pygame?

class Spritesheet:
    # utility class for loading and parsing spritesheets
    def __init__(self,height):
        return image.subsurface(pygame.Rect(x,height))