Search code examples
pythonpython-3.xpygamepygame-surface

Replace Solid Color with image Pygame


I use this code to create rectangle with solid color on background

def create_image(self):
    image = pygame.transform.scale(pygame.image.load(
        os.path.join('assets', 'ship11.png')), (ship_width, ship_height))
    self.rectangle = pygame.Surface((ship_height, ship_width), pygame.SRCALPHA)
    self.rectangle.fill(pygame.Color('dodgerblue'))

how I can use picture that I load in first line in this function in rectangle that I created

Thanks in advance


Solution

  • self.rectangle is a pygame.Surface. Use the blit method to draw a source Surface onto a Surface object:

    self.rectangle.blit(image, (0, 0))
    

    Function create_image:

    def create_image(self):
        image = pygame.transform.scale(pygame.image.load(
            os.path.join('assets', 'ship11.png')), (ship_width, ship_height))
            
        self.rectangle = pygame.Surface((ship_width, ship_height), pygame.SRCALPHA)
            self.rectangle.fill(pygame.Color('dodgerblue'))
    
        self.rectangle.blit(image, (0, 0))