How to use the mouse to scale and rotate an image in PyGame?


Pygame is a powerful library for creating 2D games and graphical applications in Python. It provides a wide range of functionalities, including the ability to manipulate and transform images. In this article, we will explore how to use the mouse to scale and rotate an image in Pygame.

Prerequisites

Before understanding the process of scaling and rotating images, it's essential to have a basic understanding of Pygame and its event-handling mechanism. Also, make sure you have Pygame installed in your Python environment. You can install it using pip with the command

pip install pygame

Setting Up the Pygame Window

To get started, let's create a Pygame window that will display our image and handle mouse events. we can begin by importing the Pygame modules

import pygame
import sys

Initialize Pygame and create a window with a specific width and height

We set the width and height variables to 800 and 600, respectively, but feel free to adjust these values to suit your needs. Now, we need to handle the main game loop that will continuously update the window:

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

The game loop keeps the window open until the user closes it by clicking the close button. If the user clicks the close button, we exit the program by calling pygame.quit() and sys.exit().

Loading and Displaying an Image

To load and display an image, we need to import it into our Pygame program. Place the image file in the same directory as your Python script. For this example, let's assume the image file is called "image.png". We can load and display the image using the following code:

The pygame.image.load() function loads the image file, and image.get_rect() returns a rectangle object representing the dimensions and position of the image. We use the screen.blit() function to draw the image onto the screen surface. Finally, pygame.display.flip() updates the display to show the image.

image = pygame.image.load("image.png")
image_rect = image.get_rect()
screen.blit(image, image_rect)
pygame.display.flip()

Scaling the Image

Now after displaying our image, let's proceed to scale it using the mouse. We'll use the mouse scroll wheel to control the scaling factor.

Example

In the below example, we used a scale_factor variable to keep track of the image's scaling. When the mouse scroll wheel is scrolled up (event.button == 4), we increase the scale_factor by 0.1. Conversely, when the scroll wheel is scrolled down (event.button == 5), we decrease the scale_factor by 0.1.

We then use the pygame.transform.scale() function to resize the original image based on the scale_factor. The width and height of the scaled image are calculated by multiplying the original dimensions by the scale_factor.

The scaled_image_rect is updated to ensure that the image remains centered after scaling. We clear the screen using screen.fill((0, 0, 0)) to remove the previous image, and then draw the scaled image using screen.blit().

import pygame
import sys

# Initialize Pygame
pygame.init()

# Set up the Pygame window
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Image Scaling Demo")

# Load and display the image
image = pygame.image.load("image.png")
image_rect = image.get_rect()
screen.blit(image, image_rect)
pygame.display.flip()

# Set up scaling variables
scale_factor = 1.0

# Game loop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 4:  # Scrolling up
                scale_factor += 0.1
            elif event.button == 5:  # Scrolling down
                scale_factor -= 0.1

    scaled_image = pygame.transform.scale(
        image, (int(image_rect.width * scale_factor), int(image_rect.height * scale_factor))
    )
    scaled_image_rect = scaled_image.get_rect(center=image_rect.center)

    screen.fill((0, 0, 0))  # Clear the screen
    screen.blit(scaled_image, scaled_image_rect)
    pygame.display.flip()

Output

Note:When we run this code, it will display the image in a Pygame window. You can use the mouse scroll wheel to scale the image up and down. Scrolling up increases the scale by 0.1, and scrolling down decreases the scale by 0.1. The scaled image will be continuously updated and displayed in the Pygame window.

Rotating the Image

Now, let's implement the rotation functionality using the mouse. We will use the mouse motion to control the angle of rotation.

Example

In the below example, we used a rotation_angle variable to keep track of the image's rotation. When the mouse is moved while the left button is pressed (event.type == pygame. MOUSEMOTION and pygame.mouse.get_pressed()[0]), we adjust the rotation_angle based on the relative x-coordinate motion (event.rel[0]). Dividing it by 10 provides a smoother rotation experience.

The pygame.transform.rotate() function is used to rotate the scaled image based on the rotation_angle. Similar to scaling, we update the rotated_image_rect to keep the image centered after rotation.

import pygame
import sys

# Initialize Pygame
pygame.init()

# Set up the Pygame window
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Image Rotation Demo")

# Load and display the image
image = pygame.image.load("image.png")
image_rect = image.get_rect()
screen.blit(image, image_rect)
pygame.display.flip()

# Set up rotation variables
rotation_angle = 0.0

# Game loop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 4:  # Scrolling up
                rotation_angle += 10
            elif event.button == 5:  # Scrolling down
                rotation_angle -= 10

    rotated_image = pygame.transform.rotate(image, rotation_angle)
    rotated_image_rect = rotated_image.get_rect(center=image_rect.center)

    screen.fill((0, 0, 0))  # Clear the screen
    screen.blit(rotated_image, rotated_image_rect)
    pygame.display.flip()

Output

Conclusion

In this article, we discussed how to use the mouse to scale and rotate an image in Pygame. By using the mouse scroll wheel, we can dynamically adjust the scaling factor and witness the image transform in real-time. Similarly, by tracking mouse movements and clicks, we can effortlessly rotate the image, providing an interactive and engaging user experience.

Updated on: 13-Oct-2023

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements