pygame image background does not match main background

自闭症网瘾萝莉.ら 提交于 2021-01-30 04:48:51

问题


I have an image with a transparent background. When I blit the image on to the background of my game the transparent background appears on the screen (see image below)

here is my code:

import sys
import pygame

def runGame():
    """ Function for running pygame """

    pygame.init()
    screen = pygame.display.set_mode((1200, 800))
    pygame.display.set_caption("Car Simulator")
    image = pygame.image.load('./car1.bmp').convert()

    bg_color = (230,230,230)

    # Start main loop for the game
    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
        

        screen.blit(image, (50,100))
        
        pygame.display.flip()


runGame()

At first I thought it was because I was not using the convert() method. However I'm still having the same issue. Any ideas on how I can get the background of the image to match the background of the screen. Any help would be appreciated. Thank you.


回答1:


If the background has a uniform color, then you can set the transparent colorkey by pygame.Surface.set_colorkey. For instnace if the background is the white (255, 255, 255):

image = pygame.image.load('./car1.bmp').convert()
image.set_colorkey((255, 255, 255))

Anyway that won't solve the issue if the background has multiple colors.

I recommend to use an image format which supports per pixel alpha. For instance PNG (Portable Network Graphics):

image = pygame.image.load('./car1.png').convert_alpha()

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



来源:https://stackoverflow.com/questions/62689244/pygame-image-background-does-not-match-main-background

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