透明度

pygame 支持 3 种透明度:colorkeys,Surface alphas 和 per-pixel alphas。

Colorkeys

使颜色完全透明,或更准确,使颜色不是 blit。如果你的图像里面有黑色矩形,你可以设置一个颜色键,以防止黑色的颜色。

BLACK = (0, 0, 0)
my_image.set_colorkey(BLACK)  # Black colors will not be blit.

Surface 只能有一个 colorkey。设置另一个颜色键将覆盖前一个颜色键。Colorkeys 不能具有不同的 alpha 值,它只能使颜色不可见。

StackOverflow 文档

表面 alphas

使整个 Surface 透明化为 alpha 值。使用此方法,你可以使用不同的 Alpha 值,但它会影响整个 Surface。

my_image.set_alpha(100)  # 0 is fully transparent and 255 fully opaque.

StackOverflow 文档

每像素 alpha

使 Surface 中的每个像素都透明化为单独的 alpha 值。这为你提供了最大的自由度和灵活性,但也是最慢的方法。此方法还要求将 Surface 创建为每像素 alpha 表面,并且颜色参数需要包含第四个 alpha 整数。

size = width, height = (32, 32)
my_image = pygame.Surface(size, pygame.SRCALPHA)  # Creates an empty per-pixel alpha Surface.

如果颜色包含第四个 alpha 值,Surface 现在将绘制透明度。

BLUE = (0, 0, 255, 255)
pygame.draw.rect(my_image, BLUE, my_image.get_rect(), 10)

与其他曲面不同,此曲面默认颜色不是黑色而是透明。这就是为什么中间的黑色矩形消失了。

StackOverflow 文档

结合 colorkey 和 Surface alpha

可以组合 Colorkeys 和 Surface alphas,但是每像素 alpha 不能。如果你不希望每像素 Surface 的性能降低,这可能很有用。

purple_image.set_colorkey(BLACK)
purple_image.set_alpha(50)

StackOverflow 文档

完整代码

将其复制到一个空文件中并运行它。按键 1,2,3 或 4 可显示图像。多次按 2,3 或 4 可使它们更不透明。

import pygame
pygame.init()

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255, 50)  # This color contains an extra integer. It's the alpha value.
PURPLE = (255, 0, 255)

screen = pygame.display.set_mode((200, 325))
screen.fill(WHITE)  # Make the background white. Remember that the screen is a Surface!
clock = pygame.time.Clock()

size = (50, 50)
red_image = pygame.Surface(size)
green_image = pygame.Surface(size)
blue_image = pygame.Surface(size, pygame.SRCALPHA)  # Contains a flag telling pygame that the Surface is per-pixel alpha
purple_image = pygame.Surface(size)

red_image.set_colorkey(BLACK)
green_image.set_alpha(50)
# For the 'blue_image' it's the alpha value of the color that's been drawn to each pixel that determines transparency.
purple_image.set_colorkey(BLACK)
purple_image.set_alpha(50)

pygame.draw.rect(red_image, RED, red_image.get_rect(), 10)
pygame.draw.rect(green_image, GREEN, green_image.get_rect(), 10)
pygame.draw.rect(blue_image, BLUE, blue_image.get_rect(), 10)
pygame.draw.rect(purple_image, PURPLE, purple_image.get_rect(), 10)

while True:
    clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_1:
                screen.blit(red_image, (75, 25))
            elif event.key == pygame.K_2:
                screen.blit(green_image, (75, 100))
            elif event.key == pygame.K_3:
                screen.blit(blue_image, (75, 175))
            elif event.key == pygame.K_4:
                screen.blit(purple_image, (75, 250))

    pygame.display.update()