如何在pygame中创建一个透明背景的表面

时间:2020-12-21 12:45:28

Can someone give me some example code that creates a surface with a transparent background in pygame?

有人可以给我一些示例代码,在pygame中创建一个透明背景的表面吗?

2 个解决方案

#1


30  

This should do it:

这应该这样做:

image = pygame.Surface([640,480], pygame.SRCALPHA, 32)
image = image.convert_alpha()

Make sure that the color depth (32) stays explicitly set else this will not work.

确保颜色深度(32)保持明确设置,否则这将不起作用。

#2


9  

You can also give it a colorkey, much like GIF file transparency. This is the most common way to make sprites. The original bitmap has the artwork, and has a certain color as background that will not be drawn, which is the colorkey:

您也可以给它一个颜色键,就像GIF文件透明度一样。这是制作精灵的最常用方法。原始位图具有图稿,并且具有某种颜色作为背景,不会被绘制,这是colorkey:

surf.set_colorkey((255,0,255)) // Sets the colorkey to that hideous purple

Surfaces that uses colorkey instead of alpha are a lot faster to blit since they don't require any blend math. The SDL surface uses a simple bitmask when it has a colorkey set, which blits practically without overhead.

使用colorkey而不是alpha的曲面要快得多,因为它们不需要任何混合数学运算。 SDL表面在具有颜色键集时使用简单的位掩码,该颜色键实际上没有开销。

#1


30  

This should do it:

这应该这样做:

image = pygame.Surface([640,480], pygame.SRCALPHA, 32)
image = image.convert_alpha()

Make sure that the color depth (32) stays explicitly set else this will not work.

确保颜色深度(32)保持明确设置,否则这将不起作用。

#2


9  

You can also give it a colorkey, much like GIF file transparency. This is the most common way to make sprites. The original bitmap has the artwork, and has a certain color as background that will not be drawn, which is the colorkey:

您也可以给它一个颜色键,就像GIF文件透明度一样。这是制作精灵的最常用方法。原始位图具有图稿,并且具有某种颜色作为背景,不会被绘制,这是colorkey:

surf.set_colorkey((255,0,255)) // Sets the colorkey to that hideous purple

Surfaces that uses colorkey instead of alpha are a lot faster to blit since they don't require any blend math. The SDL surface uses a simple bitmask when it has a colorkey set, which blits practically without overhead.

使用colorkey而不是alpha的曲面要快得多,因为它们不需要任何混合数学运算。 SDL表面在具有颜色键集时使用简单的位掩码,该颜色键实际上没有开销。