如何将精灵从矩形更改为图像?

时间:2019-04-12 00:36:27

标签: python image pygame pygame-surface

所以我从互联网(http://programarcadegames.com/python_examples/f.php?file=platform_moving.py)复制了一些代码,只是为了尝试pygame ...

我尝试将self.image.fill(BLUE)替换为self.rect = pygame.image.load("TheArrow.png")

这是我的代码的一小段。.

 def __init__(self):
        """ Constructor function """

        # Call the parent's constructor
        super().__init__()

        # Create an image of the block, and fill it with a color.
        # This could also be an image loaded from the disk.
        width = 40
        height = 60
        self.image = pygame.Surface([width, height])
        self.image.fill(BLUE)
        self.rect = pygame.image.load("TheArrow.png")

        # Set a referance to the image rect.
        self.rect = self.image.get_rect()

        # Set speed vector of player
        self.change_x = 0
        self.change_y = 0

        # List of sprites we can bump against
        self.level = None

这是原始代码...

def __init__(self):
        """ Constructor function """

        # Call the parent's constructor
        super().__init__()

        # Create an image of the block, and fill it with a color.
        # This could also be an image loaded from the disk.
        width = 40
        height = 60
        self.image = pygame.Surface([width, height])
        self.image.fill(RED)

        # Set a referance to the image rect.
        self.rect = self.image.get_rect()

        # Set speed vector of player
        self.change_x = 0
        self.change_y = 0

        # List of sprites we can bump against
        self.level = None

我希望显示图像TheArrow.png而不是矩形。...

1 个答案:

答案 0 :(得分:2)

Rect对象并不意味着要存储图像。 pygame.image.load()返回带有图像的Surface。它可以直接使用,也可以在另一个Surface上使用。

 def __init__(self):
    """ Constructor function """

    # Call the parent's constructor
    super().__init__()

    width = 40
    height = 60
    self.image = pygame.image.load("TheArrow.png") #use the image Surface directly
    self.rect = self.image.get_rect()
    #the rest as in the original code

或:

 def __init__(self):
    """ Constructor function """

    # Call the parent's constructor
    super().__init__()

    width = 40
    height = 60
    myimage = pygame.image.load("TheArrow.png")
    self.image = pygame.Surface([width, height])
    self.image.blit(myimage) #blit the image on an existing surface
    self.rect = self.image.get_rect()
    #the rest as in the original code

在前一种情况下,Surface(与之关联的rect,可以通过self.image.get_rect()获得)的大小与加载的图像文件相同。
在后者中,您使用[with, height]设置大小。如果这些与图像尺寸不符,则图像将被剪切(如果更大)。

顺便说一下,将Surface拖到另一个Surface上就是您在屏幕上显示Surface的方法。在pygame中,屏幕只是另一个Surface,有点特殊。

请查看intro tutorial,以了解更多信息。