python - 需要在 Pygame 中的表面上进行 blit 透明度

标签 python pygame

我想使用 Pygame 在我的游戏中产生盲目的影响。我正在考虑制作一个表面,用黑色填充它,然后删除玩家所在表面上的一圈颜​​色,​​以便您可以看到玩家。我也想对 torch 做同样的事情。我想知道我是否能够在 Pygame 中删除表面的一部分。

最佳答案

您可以创建一个带有 alpha channel 的表面(传递 pygame.SRCALPHA 标志),用不透明颜色填充它,然后在其上绘制一个透明颜色的形状(alpha 值为 0) 。

import pygame as pg


pg.init()
screen = pg.display.set_mode((800, 600))
clock = pg.time.Clock()
BLUE = pg.Color('dodgerblue4')
# I just create the background surface in the following lines.
background = pg.Surface(screen.get_size())
background.fill((90, 120, 140))
for y in range(0, 600, 20):
    for x in range(0, 800, 20):
        pg.draw.rect(background, BLUE, (x, y, 20, 20), 1)

# This dark gray surface will be blitted above the background surface.
surface = pg.Surface(screen.get_size(), pg.SRCALPHA)
surface.fill(pg.Color('gray11'))

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.MOUSEMOTION:
            surface.fill(pg.Color('gray11'))  # Clear the gray surface ...
            # ... and draw a transparent circle onto it to create a hole.
            pg.draw.circle(surface, (255, 255, 255, 0), event.pos, 90)

    screen.blit(background, (0, 0))
    screen.blit(surface, (0, 0))

    pg.display.flip()
    clock.tick(30)

pg.quit()

您还可以使用另一个表面而不是pygame.draw.circle来实现此效果。例如,您可以在图形编辑器中创建带有一些透明部分的白色图像,并将 BLEND_RGBA_MIN 作为special_flags 参数传递给 Surface.blit当你将它传输到灰色表面时。

brush = pg.image.load('brush.png').convert_alpha()

# Then in the while or event loop.
surface.fill(pg.Color('gray11'))
surface.blit(brush, event.pos, special_flags=pg.BLEND_RGBA_MIN)

关于python - 需要在 Pygame 中的表面上进行 blit 透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49395087/

相关文章:

python - 带有三元运算符的 Walrus 运算符的正确语法是什么?

python - Pygame 不返回操纵杆轴移动而不显示

python - 无法导入类

Python - 如何一次读取文件一个字符?

python - pyzmq 非阻塞套接字

python - 根据 Google BigQuery 中的查询结果创建表

python - Vector2 乘法导致 python 中的段错误

python - 如何在pygame中存储对象先前的x位置(坐标)?

python - Pygame 播放列表在后台连续播放

python - 如何转换图像的背景颜色以匹配 Pygame 窗口的颜色?