6

您好我想在 pygame 非矩形剪切区域(在本例中为字符“P”)中设置,它会受到严格限制,在哪里绘制另一个对象。

有什么选择吗?

多谢

4

2 回答 2

7

让我们看看我是否正确理解了您的问题:您想将图像“blit”到表面上,但是通过仅允许源的某些像素实际上最终出现在表面上的掩码进行操作?

我遇到了这个精确的问题,起初我认为这只能通过 PIL 来解决。然而,经过一些阅读和实验,事实证明它实际上可以在 pygame 相当晦涩的“特殊标志”的帮助下完成。下面是一个希望能做你想做的功能。

def blit_mask(source, dest, destpos, mask, maskrect):
    """
    Blit an source image to the dest surface, at destpos, with a mask, using
    only the maskrect part of the mask.
    """
    tmp = source.copy()
    tmp.blit(mask, maskrect.topleft, maskrect, special_flags=pygame.BLEND_RGBA_MULT)
    dest.blit(tmp, destpos, dest.get_rect().clip(maskrect))

面具应该是白色的,你希望它是透明的,否则是黑色的。

于 2011-05-09T19:42:00.877 回答
4

这是完整的代码,它在“Hello World!:D”文本上显示 2 个矩形。享受。

import pygame, sys, time
from pygame.constants import QUIT
pygame.init()

windowSurface = pygame.display.set_mode((800, 600), 0, 32)
pygame.display.set_caption('Hello World!')

WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

basicFont = pygame.font.SysFont("Times New Roman", 100)

text = basicFont.render('Hello world! :D', True, WHITE)

def blit_mask(source, dest, destpos, mask, maskrect):

        """
        Blit an source image to the dest surface, at destpos, with a mask, using
        only the maskrect part of the mask.
        """
        windowSurface.fill(WHITE)
        tmp = source.copy()

        tmp.blit(mask, destpos, maskrect, special_flags=pygame.BLEND_RGBA_MULT)  # mask 1 green


        tmp.blit(red, (destpos[0]+100,0), maskrect, special_flags=pygame.BLEND_RGBA_MULT)  # mask 2 red

        dest.blit(tmp, (0,0), dest.get_rect().clip(maskrect))

        pygame.display.update()

red = pygame.Surface((200,100))
red.fill(RED)

green = pygame.Surface((100,100),0)
green.fill(GREEN)

for a in range(700):
    blit_mask(text, windowSurface , (a,0), green, (0,0,800,600))

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
于 2011-05-10T22:00:33.287 回答