python - 使用 Convert_alpha 在 Pygame 中使图像背景透明

标签 python pygame

我试图在 Pygame 脚本中使图像的背景透明。现在我的游戏背景是黑色的,而不是透明的。我在其他地方读到可以使用 convert_alpha,但它似乎不起作用。

这是我的代码(相关部分):

import PIL
gameDisplay = pygame.display.set_mode((display_width, display_height))
img = pygame.image.load('snakehead1.bmp').convert_alpha(gameDisplay)

我做错了什么?提前致谢!

最佳答案

要使图像透明,您首先需要具有 alpha 值的图像。确保它符合这个标准!我注意到我的图像在保存为 bmp 时不会保存 alpha 值。显然,the bmp format do not have native transparency support .

如果它确实包含 alpha,您应该能够使用 convert_alpha() 方法返回具有每像素 alpha 的 Surface。您不需要向此方法传递任何内容;如果没有给出参数 the new surface will be optimized for blitting to the current display .

下面是演示这一点的示例代码:

import pygame
pygame.init()

screen = pygame.display.set_mode((100, 100))
image = pygame.image.load("temp.png").convert_alpha()

while True:
    screen.fill((255, 255, 255))

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

    screen.blit(image, (0, 0))
    pygame.display.update()

还有我的图像(“temp.png”):

enter image description here

如果它不包含 alpha,有两个简单的修复方法。

  1. 使用不同的文件格式(例如 png)保存图像。
  2. 使用颜色键。如果您只需要删除背景,则此方法有效。只需添加代码行 image.set_colorkey((0, 0, 0)) 即可,这将使所有黑色透明。

关于python - 使用 Convert_alpha 在 Pygame 中使图像背景透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39932138/

相关文章:

Python 非特定写入异常

python - 获取百分比和计数 Python

python - sqlalchemy:每次提交都需要回滚吗?

python - Pygame Clock - 它可以运行多长时间?

python - 简单函数内的意外行为,找不到原因

python - 如何从shopee网站抓取商品?

python - 有没有办法告诉 gedit .sage 文件应该始终突出显示为 Python 代码?

python-3.x - 为什么我的程序停止响应并崩溃?

python - Pygame 井字游戏逻辑?我该怎么做

python - 使用 pygame 创建 slider