Search code examples
pythonimagepygameblitpygame-surface

How do I blit an image to a surface in pygame that's the same size as a Rectangle


I'm making a game with pygame and each Sprite has a rectangle and an image. How would I blit this image to a surface so that it's the same size as the rectangle?

pygame.init()
screen = pygame.display.set_mode((720, 480))
pygame.display.set_caption('My game')

background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))

charRect = pygame.Rect((0,0),(10, 10))
print os.path.abspath("airbender.png")
charImage = pygame.image.load(os.path.abspath("ImageName.png"))
charImage = charImage.convert()

background.blit(charImage, charRect) #This just makes it in the same location
                                     #and prints it the same size as the image

screen.blit(background,(0,0))
pygame.display.flip()

Also why is that last pygame.display.flip() necessary?


Solution

  • You should do something like:

    pygame.init()
    screen = pygame.display.set_mode((720, 480))
    pygame.display.set_caption('My game')
    
    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill((250, 250, 250))
    
    charRect = pygame.Rect((0,0),(10, 10))
    print os.path.abspath("airbender.png")
    charImage = pygame.image.load(os.path.abspath("ImageName.png"))
    charImage = pygame.transform.scale(charImage, charRect.size)
    charImage = charImage.convert()
    
    background.blit(charImage, charRect) #This just makes it in the same location
                                         #and prints it the same size as the image
    
    screen.blit(background,(0,0))
    pygame.display.flip()