【问题标题】:Transparent background not disappearing when displayed on pygame window在pygame窗口上显示时透明背景不会消失
【发布时间】:2020-11-11 03:56:19
【问题描述】:

我正在创建一款汽车游戏,但遇到了一个问题。我在代码中添加了具有透明背景的汽车图像,但汽车出现在屏幕上透明背景可见。我想让背景消失。这是图片的链接:https://www.pngfind.com/mpng/bboJib_car-top-view-png-audi-transparent-png/

代码如下:

import pygame
pygame.init()
import pygame
pygame.init()

black = (0, 0, 0)

#screen
screen_width = 600
screen_length = 800
screen = pygame.display.set_mode((screen_length, screen_width))
clock = pygame.time.Clock()
FPS = 60

#the car i am having trouble with
car2Img = pygame.image.load('car2.png')
car2_X = 0
car2_Y = 0 
carX_change = 0

def car2(x, y):
    screen.blit(car2Img, (x, y))



running = True
while running:
    screen.fill((119, 118, 110))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False


    car2(car2_X, car2_Y)
    clock.tick(FPS)
    pygame.display.update()

pygame.quit() 

【问题讨论】:

  • 试试car2Img = pygame.image.load('car2.png').convert_alpha()
  • 另外,pygame不需要导入和初始化两次
  • 我尝试添加 .convert_alpha() 但由于某种原因它保持不变。
  • 下载的图片还有灰白背景的方块吗?没有它们,我无法从该链接下载图片。
  • 是的,图像仍然有白色和灰色的背景方块。我所做的只是按“将图像另存为”并调整其大小。

标签: python pygame 2d-games python-3.8 pygame-surface


【解决方案1】:

为了从 png 图像中删除背景,您必须在加载时使用 convert_alpha() 函数:

car2Img = pygame.image.load('car2.png').convert_alpha()

如果您的图像不包含 alpha,那么您可以使用颜色键来移除背景:

car2Img.set_colorkey(colorOfBackground)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    相关资源
    最近更新 更多