2

I have this code:

import pygame

class Tile(pygame.sprite.Sprite):
    def __init__(self, pos, groups):
    super().__init__(groups)
    self.loaded_image = pygame.image.load('Folder/MyImage.png')  # I added an image and I want to
    self.image = pygame.Surface((64, 64))  # <------------------------ add it here

In simple words, I have a pygame.Surface and I want to change the pygame.Surface's value to my self.loaded_image. Is it possible? Because usually pygame.Surface just displays a plain block and you can fill it with only plain colors, but instead of a plain block, I want it to be a custom image. How?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
kroogs
  • 23
  • 1
  • 3
  • You can use the `blit` function to paste a surface on top of another – mousetail Jun 28 '22 at 08:44
  • The image itself is already a surface. You don't need to put it inside another surface to blit it. If you want to rescale your image, use `pygame.transform.scale`. – The_spider Jun 28 '22 at 09:03

1 Answers1

0

First, note that if the image isn't completely solid and has a transparent background, you'll need to create a surface with an alpha channel (see How to make a surface with a transparent background in pygame):

self.image = pygame.Surface((64, 64), pygame.SRCALPHA) 

If the images are the same size, simply blit the image

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

If the images are different sizes, use pygame.transform.smoothscale

pygame.transform.smoothscale(self.loaded_image,
    self.image.get_size(), dest_surface=self.image)

or pygame.transform.scale

pygame.transform.scale(self.loaded_image, 
    self.image.get_size(), dest_surface=self.image)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174