关于python:Pygame中的透明精灵

Transparent Sprites in Pygame

我正在研究一些使用Pygame的Python代码,试图在背景顶部显示一个小的精灵(球)。 我已经完成了该部分的工作,但是我正在尝试使球形精灵的背景透明,因此它不会显示为"黑色正方形内的球形"精灵,而是以黑色像素显示 渗入显示表面。

这是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 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()

我肯定犯了一个明显的错误,但我无法弄清楚。 调用ball.set_colorkey(-1,RLEACCEL)应该拾取球形精灵左上角的颜色(碰巧是黑色),并将其用作像素颜色"不致变色"。 我错过了一步吗?

谢谢你的帮助。


有按像素的Alpha,色键Alpha和按表面Alpha。您要输入colorkey。

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

并从set_colorkey

The colorkey will be ignored if the Surface is formatted to use per pixel alpha values.

因此:使用.convert()加载图像,因为要使用颜色键。然后调用set_colorkey

Also, I saw nothing in the docs about passing"-1" as first argument to set_colorkey.

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


如何创建图像?
如果您的" ball.png"文件是透明背景上的球,而不是黑色正方形上的球,则用于by的Pygame Transparecy应该可以工作。
也就是说,从Pygame的表面文件" set_colorkey":

"如果将Surface格式化为使用每个像素的alpha值,则将忽略colorkey。可以将colorkey与整个Surface alpha值混合。"

因此,colorkey的想法是在您的图像没有每个像素的alpha值时使用它-您只是在调用"转换alpha"时确保它确实具有它。另外,我在文档中也没有看到有关将" -1"作为第一个参数传递给set_colorkey的信息。

简而言之:我的建议是使用适当的透明图像开头-并忽略" convert"," convert_alpha"," set_colorkey"等。如果您出于某种原因不使用PNG文件中的每个像素alpha,那么请以正确的方式检查此答案(甚至出于某种原因,在向屏幕显示内容时也不希望每个像素alpha):
PyGame:对Alpha图像应用透明度吗?