如何在 pygame 中添加具有我原始图像形状的白色表面?

How to add a white surface with the shape of my original image in pygame?

我正在 python 使用 pygame 制作游戏。我有一张图片,我使用 set_colorkey() 作为颜色 (0,0,0)。我没有添加 alpha 通道。它工作正常。

我想在选中的时候在上面添加一个白色透明的表面。我使用了以下代码,但它也使图像的角变白了。如何添加具有主图像形状的白色表面?

window.blit(obj.get_image(),obj.get_pos())
if obj.selected:
    white_surface = pygame.Surface(obj.size,pygame.SRCALPHA)
    white_surface.fill((255,255,255))
    white_surface.set_alpha(128)
    window.blit(white_surface,obj.get_pos())

来自我的游戏:

我想要的:

创建一个pygame.Mask form the surface and convert the mask to a white shape. A mask can be created with pygame.mask.from_surface. The pygame.Mask can be converted to a black and white pygame.Surface with the to_surface方法:

def create_white_surf(surf, alpha):
    mask = pygame.mask.from_surface(surf)
    white_surface = mask.to_surface()
    white_surface.set_colorkey((0, 0, 0))
    white_surface.set_alpha(alpha)
    return white_surface

另见 Selection and highlighting


最小示例:

repl.it/@Rabbid76/PyGame-PyGame-HighlightObject

import pygame

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

class TestObject:
    def __init__(self, x, y):
        self.image = pygame.Surface((64, 64), pygame.SRCALPHA)
        pygame.draw.circle(self.image, (0, 0, 0), (32, 32), 32)
        pygame.draw.rect(self.image, (0, 0, 0), (0, 0, 32, 64))
        pygame.draw.circle(self.image, (0, 128, 0), (32, 32), 30)
        pygame.draw.rect(self.image, (0, 128, 0), (2, 2, 30, 60))
        self.rect = self.image.get_rect(center = (x, y))
        self.size = self.rect.size
        self.selected = False
    def get_image(self):
        return self.image
    def get_pos(self):
        return self.rect.topleft

def create_white_surf(surf, alpha):
    mask = pygame.mask.from_surface(surf)
    white_surface = mask.to_surface()
    white_surface.set_colorkey((0, 0, 0))
    white_surface.set_alpha(alpha)
    return white_surface

obj_list = [TestObject(100, 150), TestObject(200, 150)]

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False    
    for obj in obj_list:
        obj.selected = obj.rect.collidepoint(pygame.mouse.get_pos())      

    window.fill((127, 127, 128))

    for obj in obj_list:
        window.blit(obj.get_image(), obj.get_pos())
        if obj.selected:
            white_surf = create_white_surf(obj.get_image(), 128)
            window.blit(white_surf, obj.get_pos())

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
exit()