简体   繁体   English

如何在pygame中制作具有透明背景的表面

[英]How to make a surface with a transparent background in pygame

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

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) 保持明确设置,否则这将不起作用。

You can also give it a colorkey, much like GIF file transparency.你也可以给它一个颜色键,就像 GIF 文件的透明度。 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:原始位图有图稿,有一定的颜色作为背景不会被绘制,这就是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.使用颜色键而不是 alpha 的表面的 blit 速度要快得多,因为它们不需要任何混合数学。 The SDL surface uses a simple bitmask when it has a colorkey set, which blits practically without overhead.当 SDL 表面有一个颜色键集时,它使用一个简单的位掩码,这实际上没有开销。

You have 3 possibilities:你有3种可能性:

  • Set a transparent color key with set_colorkey()使用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.设置SRCALPHA标志以使用包含每像素 alpha 的图像格式创建表面。 The initial value of the pixels is (0, 0, 0, 0):像素的初始值为 (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.使用convert_alpha()使用提供每像素 alpha 的图像格式创建Surface的副本。

    However, if you create a new surface and use convert_alpha() , the alpha channels are initially set to maximum.但是,如果您创建一个新表面并使用convert_alpha() ,则 alpha 通道最初设置为最大值。 The initial value of the pixels is (0, 0, 0, 255).像素的初始值为 (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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM