使用 Pygame 中的组 class 绘制精灵的一个区域或一部分

Drawing an area or portion of a sprite by using Group class in Pygame

我正在尝试使用 sprite 模块中的组 class 绘制一个区域或部分 sprite。

所以我有这个 class 来处理我的精灵:
(...是的,pygame 已经导入。)

class Sprite(pygame.sprite.Sprite):
    def __init__(self, player):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load(player)
        self.image = pygame.transform.scale(self.image, (300, 75))

        startPoint = (100, 500)
        self.rect = self.image.get_rect()
        self.rect.bottomleft = (startPoint)

然后,我使用以下方式上传精灵:

someFile = Sprite(join('res', 'file.png'))
spriteGroup = pygame.sprite.RenderUpdates(someFile)

最后用spriteGroup.draw(source)

画出来

但是,我的问题是我只想绘制一小块区域或原始文件图像的一部分。现在,我知道使用 Surface.blit() 我可以传递一个可选区域矩形,代表要绘制的源表面的较小部分。

组子class RenderUpdates有一个draw()方法,所以它不接受这种参数...还有,Surface.blit()(即使我可以使用它)不是一个选项,因为 blit() 期望坐标绘制源,但我已经在上面的 class 中定义了这些。

所以...我如何传递 (0, 0, 75, 75) 等参数来分别表示我的精灵的第一个 x 和 y、宽度和高度以仅绘制该部分?

这是我的建议。

  1. 在您的 __init__ 函数中,将图像存储在 2 个变量中。

    # Stores the original image
    self.ogimage = pygame.image.load(player)
    self.ogimage = pygame.transform.scale(self.image, (300, 75))
    # Stores the image that is displayed to the screen
    self.image = self.ogimage
    
  2. 然后,在 update 函数内部:在原始图像上设置剪辑,获取新图像,并将其存储在图像(那个会自动绘制到屏幕上)。

    def update(self):
        self.ogimage.set_clip(pygame.Rect(0, 0, 100, 100))
        self.image = self.ogimage.get_clip()
    

您的精灵图像现在大小为 100x100,从原始图像的原点开始测量。你可以fiddle加上pygame.Rect里面的set_clip得到你想要的图片。

我想办法解决了。实际上,set_clip() 方法不起作用。这是我使用 image.subsurface doc.

的方法
subsurface()  
    create a new surface that references its parent
    subsurface(Rect) -> Surface

在您的代码中,您可以尝试以下方法来绘制 Rect(0,0,75,75)

class Sprite(pygame.sprite.Sprite):
    def __init__(self, player):
        pygame.sprite.Sprite.__init__(self)

        self.original = pygame.image.load(player)
        self.original = pygame.transform.scale(self.image, (300, 75))
        self.image = self.original.subsurface(Rect(0, 0, 75, 75))
        self.rect = self.image.get_rect()

然后,在 update 函数中更新 self.imageself.rect