问题描述
在 pygame 中是否有任何方法可以在掩码内将某些内容 blit 到屏幕上.例如:如果您有一个掩码,除了左上角和全黑图像外,所有位都设置为 1,而不更改图像,您能否保持左上角(与掩码相同)清晰?只有更新掩码(而不是矩形)才会有帮助.
Is there any way in pygame to blit something to the screen inside a mask. Eg: if you had a mask where all the bits were set to 1 except for the topleft corner and a fully black image, without changing the image, could you keep the top left corner (same as the mask) clear? Only updating a mask (rather than a rect) would help to.
推荐答案
好吧,如果我正确理解你的问题,诀窍是 BLEND_RGBA_MULT
标志.
Ok, if I'm understanding your question properly, the trick is the BLEND_RGBA_MULT
flag.
我决定亲自测试一下,因为我很好奇.我从这张图片开始:
I decided to test this for myself because I was curious. I started with this image:
我用白色制作了一张我想要显示的图像,并在我想要遮罩的地方制作了透明度.我什至给它设置了不同程度的透明度,看看我是否可以得到模糊遮罩.
I made an image with white where I wanted the image to show, and transparency where I wanted it masked. I even gave it varying levels of transparency to see if I could get fuzzy masking.
^^^ 您可能看不到图像,因为它是透明的白色,但它就在那里.您可以右键单击并下载它.
^^^ You probably can't see the image because it's white on transparent, but it's there. You can just right click and download it.
我加载了两张图片,确保使用了convert_alpha()
:
I loaded the two images, making sure to use convert_alpha()
:
background = pygame.image.load("leaves.png").convert_alpha()
mask = pygame.image.load("mask-fuzzy.png").convert_alpha()
然后为了遮罩图像,我复制了被遮罩的图像,
Then to mask the image, I made a copy of the image being masked,
masked = background.copy()
...我使用 BLEND_RGBA_MULT
将蒙版复制到这个副本上,
...I blitted the mask onto this copy using BLEND_RGBA_MULT
,
masked.blit(mask, (0, 0), None, pygame.BLEND_RGBA_MULT)
...然后我把它画到了屏幕上.
...and I drew it to the screen.
display.blit(masked, (0, 0))
果然成功了:
这是我使用的完整代码.
Here's the complete code I used.
import pygame
from pygame.locals import *
pygame.init()
display = pygame.display.set_mode((320, 240))
background = pygame.image.load("leaves.png").convert_alpha()
mask = pygame.image.load("mask-fuzzy.png").convert_alpha()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# draw
display.fill(Color(255, 0, 255))
masked = background.copy()
masked.blit(mask, (0, 0), None, pygame.BLEND_RGBA_MULT)
display.blit(masked, (0, 0))
pygame.display.flip()
如果您想要一个可变遮罩,您可以尝试手动编辑一个 Surface 并将其用作您的遮罩.
If you want a variable mask, you could try manually editing a Surface and using that as your mask.
以下是通过编辑表面生成蒙版的示例:
Here's an example of generating a mask by editing a Surface:
mask = pygame.Surface((320, 240), pygame.SRCALPHA)
for y in range(0, 240):
for x in range(0, 320):
if (x/16 + y/16) % 2 == 0:
mask.set_at((x, y), Color("white"))
它产生了这个结果:
现在我想在游戏中使用它!
Now I want to use this in a game!
这篇关于Pygame - 有没有办法只在掩码中进行 blit 或更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!