2016-10-08 147 views
0

我想在Pygame腳本中製作圖像透明背景。現在我的遊戲背景是黑色的,而不是透明的。我讀了其他地方,我可以使用convert_alpha,但它似乎並沒有工作。使用convert_alpha在Pygame中製作圖像透明背景

這裏是我的代碼(相關部分):

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

我在做什麼錯?提前致謝!

+0

'convert_alpha' *在您的圖像中添加了一個alpha組件,因此您可以使其透明 - 但是它本身並不是。你在哪裏讀到這個?事後做了什麼? – usr2564301

回答

1

要使圖像透明,首先需要帶有alpha值的圖像。確保它符合這個標準!我注意到,當保存爲bmp時,我的圖像不保存alpha值。顯然,the bmp format do not have native transparency support

如果它確實包含alpha,您應該可以使用方法convert_alpha()來返回具有每像素alpha的曲面。你不需要傳遞任何東西給這個方法。如果沒有給出參數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)),這將使所有的黑色透明。