Make the background of an image transparent in Pygame with convert_alpha

隐身守侯 提交于 2021-01-28 20:18:01

问题


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!


回答1:


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.


来源:https://stackoverflow.com/questions/39932138/make-the-background-of-an-image-transparent-in-pygame-with-convert-alpha

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!