【问题标题】:Pygame: How to draw in non rectangle clipping areaPygame:如何在非矩形剪切区域中绘制
【发布时间】:2011-08-21 21:46:16
【问题描述】:

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

有什么办法吗?

非常感谢

【问题讨论】:

    标签: python draw pygame clip


    【解决方案1】:

    让我们看看我是否正确理解了您的问题:您想将图像“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))
    

    蒙版在您希望它透明的地方应该是白色的,否则应该是黑色的。

    【讨论】:

    • 是的,你是对的。您的代码对我帮助很大(它是多么容易:D)。谢谢。
    【解决方案2】:

    这是完整的代码,它在“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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多