【问题标题】:Need to blit transparency on a surface in Pygame需要在 Pygame 的表面上设置透明度
【发布时间】:2020-04-17 05:37:28
【问题描述】:

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

【问题讨论】:

  • 这是一个“我想要一匹小马”的问题,因为无法给出具体的技术答案,所以它在 Stack Overflow 上是题外话。您需要尝试解决此问题并展示您的代码,以便我们了解您在技术层面上尝试做什么,并展示您解决此问题的承诺。
  • 这个question 有一个可能对你有帮助的例子。
  • 谢谢(埃里克)这很有帮助,希望在我问问题之前能看到它。

标签: python pygame


【解决方案1】:

您可以创建一个带有 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()

您也可以使用另一个表面而不是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)

【讨论】:

  • 感谢您,这对您很有帮助。我每天都在学习更多关于 Pygame 和 python 的知识。
猜你喜欢
  • 2013-07-09
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多