Scale image to fit screen in Pygame Python

Here in this tutorial, we will learn how to make an image fit the size of your pygame screen.

Pygame is a widely used library in Python; Which is used for making games this in turn also means that we can add images, text, characters, soundtracks, etc to make it more interesting.

Transform image to screen size in Pygame

Here we will be using pygame.transform.scale() function to transform image to screen size.

import pygame

screen = pygame.display.set_mode((700, 500))

image = pygame.image.load("sky.png")
screenUpdate = pygame.transform.scale(image, (700, 500))

while True:
    for i in pygame.event.get():
        if i.type == pygame.QUIT:
            pygame.quit()
            exit()

    screen.blit(screenUpdate, (0, 0))

    pygame.display.update()

In the code mentioned above, we have used the following functions:

  •  pygame.display.set_mode(): This sets the pygame screen dimension.
  • pygame..image.load(): This loads the image onto the screen without specifying the dimensions.
  • pygame.transform.scale(): This transforms the image size to fit accurately with the screen.
  • pygame.quit(): Used for quitting the game whenever desired.
  • screen.blit(): This updates the screen with the image mentioned and the exact location where we want our x and y coordinates to be.
  • pygame.display.update(): In the end, this function updates the screen of all the changes that have been made so far.

Output:

Scale image to fit screen in Pygame Python

If you wish to read more about the blit() function you can visit  Pygame screen.blit example

Thus we have seen how to add a screen size image in pygame.

Leave a Reply

Your email address will not be published.