【问题标题】:Problem with alpha channels in my picture (PyGame) [duplicate]我的图片中的 alpha 通道有问题(PyGame)[重复]
【发布时间】:2021-08-24 07:07:01
【问题描述】:

目前,我正在尝试将一张图片粘贴到我的 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, y, width, height))
        image.set_colorkey(pygame.color.Color("black"))
        return image

我怎样才能把原来有alpha通道的图片放在上面?

【问题讨论】:

    标签: python pygame


    【解决方案1】:

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


    你必须使用convert_alpha 而不是convert

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

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

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

    另外创建一个具有每像素 alpha 格式的 Surface。设置 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, height), pygame.SRCALPHA)
            image.fill(pygame.color.Color("black"))
            image.blit(self.spritesheet, (0, 0), (x, y, width, 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, filename):
            self.spritesheet = pygame.image.load(filename).convert_alpha()
    
        def get_image(self, x, y, width, height):
            return image.subsurface(pygame.Rect(x, y, width, height))
    

    【讨论】:

    • 制作convert_alpha()的问题在于它与我发布的第二张图片相同。
    • @Jouca 我还没说完。
    猜你喜欢
    • 2020-03-21
    • 1970-01-01
    • 2010-10-11
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2023-02-20
    • 1970-01-01
    • 2018-04-25
    相关资源
    最近更新 更多