How can I make an Image with a transparent Backround in Pygame?

微笑、不失礼 提交于 2020-12-13 03:24:07

问题


I am fairly new to programming, so I bought the Book "Python Crash Course" by Eric Matthes. Recently, I decided to recreate the Pokemon Battle System in Pygame. So far, I have made a good enough framework to start the battle system. I picked the Pokemon Mew as a test subject. I already have the transparent backround for the picture, but pygame still shows the gray and white squares. This is my main code-file:


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

And this is my settings file for 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)

And this(https://imgur.com/a/OytJBUN) is how it turned out. How can I make the of the Picture backround transparent?


回答1:


The issue is the image format. JPEG images have no alpha channel. You can set a transparent colorkey by set_colorkey(), but the result will not satisfy you, because the JPEG is not lossless. That means due the compression, the colors will slightly change and the color key will not work correctly. For instance white color:

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

Either use set_colorkey() and a lossless image format like BMP:

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

or us the PNG format. For instance:

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



回答2:


Use a PNG with the convert_alpha() function:

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


来源:https://stackoverflow.com/questions/62623341/how-can-i-make-an-image-with-a-transparent-backround-in-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!