【问题标题】:pygame image background does not match main backgroundpygame 图像背景与主背景不匹配
【发布时间】:2020-07-02 04:52:46
【问题描述】:

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

这是我的代码:

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

【问题讨论】:

    标签: python pygame pygame-surface


    【解决方案1】:

    如果背景颜色统一,则可以通过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?

    【讨论】:

      猜你喜欢
      • 2022-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-10
      • 2011-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多