我正在尝试使用sprite模块中的Group类绘制sprite的一个区域或部分。
所以我有这个班来处理我的精灵:
(...是的,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()
我可以传递一个可选的区域矩形,表示要绘制的源Surface的一小部分。
Group子类 RenderUpdates 有一个draw()
方法,所以它不接受这种参数......还有,Surface.blit()
(即使我可以使用它不是一个选项,因为blit()
期望坐标绘制源,但我已经从上面在我的类中定义了这些。
那么......我怎样才能传递(0, 0, 75, 75)
这样的参数来分别表示我的精灵的第一个x和y,宽度和高度来画出那个部分?
答案 0 :(得分: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
然后,在更新功能内:在原始图像上设置剪辑,获取新图像,并将其存储在图像中(自动绘制到屏幕上的图像)
def update(self):
self.ogimage.set_clip(pygame.Rect(0, 0, 100, 100))
self.image = self.ogimage.get_clip()
根据原始图像的原点测量,您的精灵图像现在尺寸为100x100。您可以使用 set_clip 中的 pygame.Rect 来获取所需的图像。
答案 1 :(得分:1)
我找到了解决问题的方法。实际上,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()
然后,更新self.image
功能内的self.rect
和update
。