简体   繁体   English

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

[英]Need to blit transparency on a surface in Pygame

I was wanting to make a blind affect in my game using Pygame.我想使用 Pygame 在我的游戏中产生盲目的影响。 I was thinking of making a surface, filling it with black, then removing a circle of color on the surface where the player is so you can see the player.我正在考虑制作一个表面,用黑色填充它,然后在玩家所在的表面上删除一个颜色圆圈,以便您可以看到玩家。 I also wanted to do the same for a torch.我也想为火炬做同样的事情。 I was wondering if i was able to erase parts of a surface in Pygame.我想知道我是否能够在 Pygame 中擦除部分表面。

You can create a surface with an alpha channel (pass the pygame.SRCALPHA flag), fill it with an opaque color and then draw a shape with a transparent color onto it (alpha value 0).您可以创建一个带有 alpha 通道的表面(传递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()

You can also achieve this effect with another surface instead of pygame.draw.circle .您也可以使用另一个表面而不是pygame.draw.circle来实现此效果。 For example you could create a white image with some transparent parts in your graphics editor and pass BLEND_RGBA_MIN as the special_flags argument toSurface.blit when you blit it onto the gray surface.例如,您可以在图形编辑器中创建带有一些透明部分的白色图像,并在将其 blit 到灰色表面时将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)

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

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