我的图像带有透明背景。当我将图像显示在游戏背景上时,透明背景出现在屏幕上(请参见下图)
这是我的代码:
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()
起初我以为是因为我没有使用convert()
方法。但是我仍然有同样的问题。关于如何获取图像背景以匹配屏幕背景的任何想法。任何帮助,将不胜感激。谢谢。
答案 0 :(得分:0)
如果背景具有统一的颜色,则可以通过pygame.Surface.set_colorkey
设置透明色键。对于背景而言,如果背景是白色(255、255、255)
image = pygame.image.load('./car1.bmp').convert()
image.set_colorkey((255, 255, 255))
如果背景有多种颜色,无论如何都无法解决问题。
我建议使用支持每个像素alpha的图像格式。例如PNG (Portable Network Graphics):
image = pygame.image.load('./car1.png').convert_alpha()
另请参阅How can I make an Image with a transparent Backround in Pygame?