Rotating and scaling images using Pygame

Key takeaways:

  • Pygame offers several methods for transforming images, including pygame.transform.scale(), which resizes an image, and pygame.transform.rotate(), which rotates an image by a specified angle.

  • Pygame provides various scaling functions like pygame.transform.scale() for general resizing, scale2x() for quick doubling, and smoothscale() for anti-aliased high-quality resizing.

  • These methods can be combined in game development to create dynamic visual effects, such as smoothly resizing or rotating game objects based on user interactions or game logic.

Pygame is a cross-platform set of Python modules for developing 2D games and graphical applications. It provides various functions to manipulate images, including rotating and scaling. Here, we will explore Pygame methods used to transform images and provide examples to understand the operations better.

The pygame.transform.scale() method

pygame.transform.scale() scales an image to a new size. The new size can be specified as a tuple of (width, height) or as a single number, which will be used as both the width and height. Run the following application to see how the method works if a new size tuple is specified:

import pygame

# Configuration
Image_width, Image_height = 700, 700
Original_position = (0, 0)
Scaled_position_1 = (150, 50)
Scaled_position_2 = (150, 250)
Image_size_1 = (150, 150)  # First scaled size
Image_size_2 = (300, 300)  # Second scaled size
Background_color = (0, 0, 0)
FPS = 30

def scale_image(image, size):
    return pygame.transform.scale(image, size)

def main():
    pygame.init()
    screen = pygame.display.set_mode((Image_width, Image_height))
    clock = pygame.time.Clock()
    running = True

    original_image = pygame.image.load('animal.png')
    scaled_image_1 = scale_image(original_image, Image_size_1)
    scaled_image_2 = scale_image(original_image, Image_size_2)

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        screen.fill(Background_color)
        screen.blit(original_image, Original_position)
        screen.blit(scaled_image_1, Scaled_position_1)
        screen.blit(scaled_image_2, Scaled_position_2)
        pygame.display.flip()
        clock.tick(FPS)

    pygame.quit()

if __name__ == "__main__":
    main()
Scaling an image using pygame.transform.scale()

Here’s an explanation:

  • Line 1: Imports the pygame module to access pygame functionalities.

  • Lines 4–9: Defines configuration constants for your pygame application.

  • Lines 11–12: Defines a function called scale_image that takes an image and a size as arguments and returns the scaled image.

  • Lines 14–18: Defines the main function that encapsulates the main logic of the application. Initializes pygame, creates the game window with dimensions specified in Widthand Height, initializes a clock to control the frame rate and sets the running variable to True to control the game loop.

  • Line 20: Loads the original image using pygame.image.load('animal.png') and stores it in the original_image variable.

  • Line 21: Scales the original image to the desired size (as specified by Image_size) using the scale_image function and stores the scaled image in the scaled_image variable.

  • Lines 23–26: The while loop continues to run as long as the running variable is True. Inside the game loop, it iterates through the list of pygame events and if a QUIT event is detected, it sets running to False to exit the loop and close the application.

  • Lines 28–32: Fills the screen with the background color specified in Bakcground_color using to clear the previous frame. Uses screen.blit() to draw the original image and scaled image. Calls pygame.display.flip() to update the display with the latest frame. Controls the frame rate using clock.tick(FPS) to limit the application to the specified frames per second.

  • Line 34: Call pygame.quit() to clean up after the loop ends and exit pygame.

  • Lines 36–37: Checks if the script is the main program and if it is, executes the main() function.

There are many other scaling methods derived from pygame.transform.scale(). We'll discuss them below.

The pygame.transform.scale_by() method

pygame.transform.scale_by() scales an image by a factor of scale_factor. For example, if you want to increase the size of an image by 2x, you could call scale_by(image, 2) as an alternative to pygame.transform.scale().

The pygame.transform.scale2x() method

pygame.transform.scale2x() scales an image to double its size in both dimensions. It is a quicker way to make an image larger if a simple 2x scale is required.

The pygame.transform.smoothscale()method

pygame.transform.smoothscale() is used for smooth scaling of images. Unlike pygame.transform.scale(), it uses anti-aliasing to create a smoother, less pixelated result. It's ideal for high-quality scaling, such as when resizing images for display or printing.

The pygame.transform.get_smoothscale_backend() method

pygame.transform.get_smoothscale_backend() returns the name of the backend pygame is using for smooth scaling. It can be useful for checking the current backend or debugging, but it's not typically used as a direct alternative to pygame.transform.scale().

In summary, each of these functions can be used as an alternative to pygame.transform.scale() based on your specific requirements. The choice depends on your particular use case and performance considerations.

The pygame.transform.rotate() method

pygame.transform.rotate() rotates an image by a specified angle. The angle is measured in degrees, and positive values rotate the image counterclockwise, while negative values rotate it clockwise. The center of the image remains the same, but the overall dimensions of the rotated image may change. This method is particularly useful for creating dynamic and interactive visual effects in games, such as spinning objects or adjusting the orientation of sprites based on movement. Run the following application to see how the method works when an angle is specified:

import pygame

pygame.init()

size = width,height = 600, 600
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()

image = pygame.image.load('animal.png')

DEFAULT_IMAGE_SIZE = (200, 200)
image = pygame.transform.scale(image, DEFAULT_IMAGE_SIZE)

# Rotate the image by any degree
image_rot = pygame.transform.rotate(image, 180)

DEFAULT_IMAGE_POSITION = (200,200)

running = False
while not running:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			running = True

	screen.fill((0, 0, 0))
	screen.blit(image, (0, 0))
	screen.blit(image_rot, DEFAULT_IMAGE_POSITION)

	pygame.display.flip()
	clock.tick(30)
Rotating an image using pygame.transform.rotate()

Here’s an explanation:

  • Line 1: Imports the pygame module to access pygame functionalities.

  • Line 3: Sets up the pygame environment using pygame.init().

  • Line 5: Defines the dimensions of the game window.

  • Line 6: Creates the game window with the specified dimensions and stores it in the screen variable.

  • Line 7: Creates a clock object to control the frame rate of the game.

  • Line 9: Loads an image from a file named animal.png and stores it in the image variable.

  • Lines 11–12: Defines the desired size for the image using DEFAULT_IMAGE_SIZE and scales the loaded image to the desired size. The new scaled images replaces the original image in the image variable.

  • Line 15: Rotates the scaled image by 180 degrees using pygame.transform.rotate(), creating a new rotated image that replaces the previous image in the image_rot variable

  • Line 17: Defines the default position (200, 200) for the image on the game window.

  • Lines 19–23: Initializes the running variable as False before starting the game loop. while not running starts a game loop that continues until the running variable remains False. In the loop, pygame.event.get() iterates through the list of pygame events. if event.type == pygame.QUIT checks if the current event is a "QUIT" event and if it is detected, it sets the running variable to True to exit the loop and close the application.

  • Line 25: Fills the screen with a black background using screen.fill().

  • Line 26: Displays scaled original image on the screen at the specified position using screen.blit().

  • Line 27: Displays rotated scaled original image on the screen at the specified position using screen.blit().

  • Line 29: Updates the display to show the latest frame using the pygame.display.flip() method.

  • Line 30: Controls the frame rate which limits the application to 30 frames per second to maintain a consistent frame rate.

All the discussed methods can be used individually or together to obtain desired image results using pygame.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How can you mirror an image in Pygame?

You can mirror or flip an image in Pygame using the pygame.transform.flip() function. This function takes three arguments: the image to be flipped, a boolean for horizontal flip, and a boolean for vertical flip. For example, to flip an image horizontally: flipped_image = pygame.transform.flip(image, True, False)


How do you change the surface size in Pygame?

To change the surface size in Pygame, you can use pygame.transform.scale() or pygame.transform.smoothscale() to resize the surface to the desired dimensions. For example: scaled_surface = pygame.transform.scale(surface, (new_width, new_height))


How do you manipulate images in Pygame?

In Pygame, you can manipulate images using various methods, such as:

Scaling: pygame.transform.scale() to resize the image.

Rotating: pygame.transform.rotate() to rotate an image by a specific angle.

Flipping: pygame.transform.flip() to mirror an image horizontally or vertically.

Smoothing: pygame.transform.smoothscale() to resize with anti-aliasing for higher quality.

These functions adjust images to fit your game or application needs.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved