Pygame 中的透明精灵

dva*_*ria 2 python pygame

我正在编写一些使用 Pygame 的 Python 代码,试图在背景顶部显示一个小精灵(一个球)。我有那部分工作,但我试图让球精灵的背景变得透明,这样它就不会显示为“黑色正方形内的球”精灵,而是显示为黑色像素不存在位块传送到显示表面。

这是我的代码:

# For sys.exit()
import sys

# Pygame imports
import pygame
from pygame.locals import *

# Initialize all the Pygame Modules
pygame.init()

# Build a screen (640 x 480, 32-bit color)
screen = pygame.display.set_mode((640,480)) 

# Create and Convert image files
# Use JPG files for lots of color, and use conver()
# Use PNG files for transparency, and use convert_alpha()
background = pygame.image.load("bg.jpg").convert()
ball = pygame.image.load("ball.png").convert_alpha()
ball.set_colorkey(-1, RLEACCEL) # Use the upper-left pixel color as transparent

# The main loop
while True:

    # 1 - Process all input events
    for event in pygame.event.get():

        # Make sure to exit if the user clicks the X box
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    # 2 - Blit images to screen (main display window)
    screen.blit(background, (0,0))
    x,y = pygame.mouse.get_pos()
    x = x - ball.get_width()/2
    y = y - ball.get_height()/2
    screen.blit(ball, (x,y))

    # 3 - Update the main screen (redraw)
    pygame.display.update()
Run Code Online (Sandbox Code Playgroud)

我肯定犯了一个明显的错误,但我无法弄清楚。调用 ball.set_colorkey(-1, RLEACCEL) 应该获取球精灵左上角的颜色(恰好是黑色)并将其用作“不进行 blit”的像素颜色。我是不是少了一步?

感谢您的帮助。

nin*_*key 5

有每像素 alpha、色键 alpha 和每表面 alpha。您要求的是 colorkey。

当您调用时,convert_alpha()它会为每像素 alpha 创建一个新表面。

并来自 set_colorkey

如果 Surface 的格式设置为使用每像素 alpha 值,则将忽略 colorkey。

因此:加载图像.convert()因为您想使用颜色键。然后打电话set_colorkey

另外,我在文档中没有看到有关将“-1”作为第一个参数传递给 set_colorkey 的内容。

这可能来自一个教程,该教程有一个 load_image 函数来获取左上角像素的颜色值。