gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:56:30 24 4
gpt4 key购买 nike

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

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

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())

来 self 的游戏:

我想要的:

最佳答案

创建一个 pygame.Mask形成表面并将蒙版转换为白色形状。可以使用 pygame.mask.from_surface 创建掩码. pygame.Mask可以转换成黑白pygame.Surfaceto_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()

关于python - 如何在pygame中添加一个具有我原始图像形状的白色表面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67884084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com