简体   繁体   English

Pygame:如何在非矩形剪贴区域中绘制

[英]Pygame: How to draw in non rectangle clipping area

Hi I would like to set in pygame non rectangle clipping area (in this case as character "P"), where it would be strict limited, where to draw another objects. 嗨,我想在pygame中设置非矩形剪贴区域(在这种情况下为字符“ P”),在该区域中将受到严格限制,并在其中绘制其他对象。

Is there any option? 有什么选择吗?

thanks a lot 非常感谢

Let's see if I correctly understand your question: you want to "blit" an image onto a surface, but do it through a mask which would only allow certain pixels of the source to actually end up on the surface? 让我们看看我是否正确理解了您的问题:您想将图像“白化”到表面上,但是要通过遮罩来实现,它只允许光源的某些像素实际最终出现在表面上?

I had this precise problem and at first I thought it would only be doable through PIL. 我遇到了这个确切的问题,起初我认为只有通过PIL才能实现。 However after some reading and experimentation, it turns out that it can actually be done with the help of pygame's rather obscure "special flags". 然而,经过一些阅读和试验,事实证明,实际上可以借助pygame相当模糊的“特殊标志”来完成此操作。 Below is a function which hopefully does what you want. 下面是一个函数,它可以完成您想要的操作。

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))

The mask should be white where you want it to be transparent and black otherwise. 如果希望蒙版透明,则蒙版应为白色,否则应为黑色。

And here is full code, that blits 2 rects on "Hello World! :D" text. 这是完整的代码,在“ Hello World!:D”文本上显示2个矩形。 Enjoy. 请享用。

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()

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

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