【问题标题】:How can I make an Image with a transparent Backround in Pygame?如何在 Pygame 中制作具有透明背景的图像?
【发布时间】:2020-10-18 17:50:47
【问题描述】:

我对编程还很陌生,所以我买了 Eric Matthes 的《Python Crash Course》一书。最近,我决定在 Pygame 中重新创建口袋妖怪对战系统。至此,我已经做了一个足够好的框架来启动战斗系统。我选择了 Pokemon Mew 作为测试对象。我已经有了图片的透明背景,但是 pygame 仍然显示灰色和白色方块。这是我的主要代码文件:


from settings import Settings
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Pykemon Battle Simulator")
    pokemon = Mew(screen)
    mixer.music.load("battle_music.mp3")
    mixer.music.play(-1)

    while True:
        screen.fill(ai_settings.bg_color)
        pokemon.blitme()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
        pygame.display.flip()

run_game()

这是我的 Mew 设置文件:

import pygame

class Mew():
    def __init__(self, screen):
        """Initialize the Pokémon Mew and it's location """
        self.screen = screen

        #Load the pokemon and get it's rect.
        self.image = image = pygame.image.load("mew.jpg").convert_alpha()
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()
        #Start each new Pokemon at the bottom of the screen
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom
    
    def blitme(self):
        """Draw the pokemon's current location"""
        self.screen.blit(self.image, self.rect)

结果是这样的(https://imgur.com/a/OytJBUN)。如何使图片背景透明?

【问题讨论】:

    标签: python pygame pygame-surface


    【解决方案1】:

    问题在于图像格式。 JPEG 图像没有 Alpha 通道。您可以通过set_colorkey() 设置透明色键,但结果不会让您满意,因为JPEG 不是无损的。这意味着由于压缩,颜色会略有变化,颜色键将无法正常工作。例如白色:

    self.image = image = pygame.image.load("mew.jpg")
    self.image.set_colorkey((255, 255, 255))
    

    使用set_colorkey() 和像BMP 这样的无损图像格式:

    self.image = image = pygame.image.load("mew.bmp")
    self.image.set_colorkey((255, 255, 255))
    

    或者我们PNG 格式。例如:

    image = pygame.image.load("mew.png").convert_alpha()
    

    【讨论】:

    • 谢谢你的建议^^我用PNG格式试过了,但由于某种原因它不能正常工作(可能是因为我很愚蠢,但谁知道)
    • @PokemasterLink 当然,png 图像必须具有适当的 alpha 通道。背景是透明的吗?
    【解决方案2】:

    使用带有 convert_alpha() 函数的 PNG:

    image = pygame.image.load("image.png").convert_alpha()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-24
      • 2011-12-05
      • 2012-05-26
      • 2012-07-07
      • 2020-09-07
      • 1970-01-01
      • 2011-03-14
      相关资源
      最近更新 更多