有人能给我一些在pygame中创建透明背景表面的示例代码吗?
这应该可以解决:
image = pygame.Surface([640,480], pygame.SRCALPHA, 32)
image = image.convert_alpha()
确保颜色深度(32)保持明确设置,否则这将无法正常工作。
您还可以为其设置颜色键,就像GIF文件透明度一样。这是制作精灵的最常见方式。原始位图具有艺术作品,并且具有某种背景色,该背景色不会被绘制,这就是颜色键:
surf.set_colorkey((255,0,255)) // Sets the colorkey to that hideous purple
使用颜色键而不是alpha通道的表面在blit(图像复制)时速度更快,因为它们不需要进行任何混合运算。当SDL表面设置了颜色键时,它使用一个简单的位掩码进行blit,几乎没有任何额外开销。
您有三个选择:
Set a transparent color key with set_colorkey()
The color key specifies the color that is treated as transparent. For example, if you have an image with a black background that should be transparent, set a black color key:
my_surface.set_colorkey((0, 0, 0))
You can enable additional functions when creating a new surface. Set the SRCALPHA
flag to create a surface with an image format that includes a per-pixel alpha. The initial value of the pixels is (0, 0, 0, 0):
my_surface = pygame.Surface((width, height), pygame.SRCALPHA)
Use convert_alpha()
to create a copy of the Surface with an image format that provides alpha per pixel.
However, if you create a new surface and use convert_alpha()
, the alpha channels are initially set to maximum. The initial value of the pixels is (0, 0, 0, 255). You need to fill the entire surface with a transparent color before you can draw anything on it:
my_surface = pygame.Surface((width, height))
my_surface = my_surface.convert_alpha()
my_surface.fill((0, 0, 0, 0))
image = pygame.Surface([640, 480], pygame.SRCALPHA)
就足够了。 - Jaycecloud_color = (255, 255, 255, 120)
,其中最后一个值的范围是0到255。 - Ethan McRae