我试图在 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”):
如果它不包含 alpha,有两个简单的修复方法。
- 使用不同的文件格式(例如 png)保存图像。
- 使用颜色键。如果您只需要删除背景,则此方法有效。只需添加代码行
image.set_colorkey((0, 0, 0))
即可,这将使所有黑色透明。
关于python - 使用 Convert_alpha 在 Pygame 中使图像背景透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39932138/