pygame 图像背景与主背景不匹配 [英] pygame image background does not match main background

查看:67
本文介绍了pygame 图像背景与主背景不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张背景透明的图片.当我将图像 blit 到我的游戏背景上时,透明背景出现在屏幕上(见下图)

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)

这是我的代码:

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() 方法.但是我仍然有同样的问题.关于如何使图像背景与屏幕背景相匹配的任何想法.任何帮助,将不胜感激.谢谢.

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.

推荐答案

如果背景有统一的颜色,那么可以通过pygame.Surface.set_colorkey.例如,如果背景是白色 (255, 255, 255):

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.

我建议使用支持每像素 alpha 的图像格式.例如PNG(便携式网络图形):

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


<子>

另见 如何在 Pygame 中制作带有透明背景的图像?

这篇关于pygame 图像背景与主背景不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆