使用 convert_alpha 在 Pygame 中使图像的背景透明 [英] Make the background of an image transparent in Pygame with convert_alpha

查看:128
本文介绍了使用 convert_alpha 在 Pygame 中使图像的背景透明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

导入PILgameDisplay = pygame.display.set_mode((display_width, display_height))img = pygame.image.load('snakehead1.bmp').convert_alpha(gameDisplay)

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

解决方案

要使图像透明,您首先需要具有 alpha 值的图像.确保它符合这个标准!我注意到我的图像在另存为 bmp 时没有保存 alpha 值.显然,

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

  1. 使用不同的文件格式保存图像,例如 png.
  2. 使用色键.如果您只需要删除背景,这会起作用.就像把代码行 image.set_colorkey((0, 0, 0)) 一样简单,这将使所有黑色透明.

I am trying to make the background of an image transparent in a Pygame script. Now the background in my game is black, instead of transparent. I read somewhere else that I could use convert_alpha, but it doesn't seem to work.

Here is (the relevant part of) my code:

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

What am I doing wrong? Thanks in advance!

解决方案

To make an image transparent you first need an image with alpha values. Be sure that it meets this criteria! I noticed that my images doesn't save the alpha values when saving as bmp. Apparently, the bmp format do not have native transparency support.

If it does contain alpha you should be able to use the method convert_alpha() to return a Surface with per-pixel alpha. You don't need to pass anything to this method; if no arguments are given the new surface will be optimized for blitting to the current display.

Here's an example code demonstrating this:

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

And my image ("temp.png"):

If it doesn't contain alpha there are two easy fixes.

  1. Save the image with a different file format, like png.
  2. Use colorkeys. This works if you only need to remove the background. It is as easy as putting the line of code image.set_colorkey((0, 0, 0)), which will make all black colors transparent.

这篇关于使用 convert_alpha 在 Pygame 中使图像的背景透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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