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 required modules and setting up the basic window structure ?

import pygame
import sys
import math

# 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 Transformation Demo")

# Create a simple colored rectangle as our image
image = pygame.Surface((100, 100))
image.fill((255, 100, 100))  # Red color
image_rect = image.get_rect(center=(width//2, height//2))

print("Pygame window created successfully")
Pygame window created successfully

Scaling an Image with Mouse Scroll

Now let's implement image scaling using the mouse scroll wheel. We'll use a scale factor to control the image size ?

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")

# Create a simple colored rectangle as our image
original_image = pygame.Surface((100, 100))
original_image.fill((255, 100, 100))  # Red color
image_rect = original_image.get_rect(center=(width//2, height//2))

# Set up scaling variables
scale_factor = 1.0
clock = pygame.time.Clock()

# Game loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 4:  # Scroll up
                scale_factor = min(scale_factor + 0.1, 3.0)  # Maximum scale 3x
            elif event.button == 5:  # Scroll down
                scale_factor = max(scale_factor - 0.1, 0.1)  # Minimum scale 0.1x

    # Scale the image
    new_width = int(original_image.get_width() * scale_factor)
    new_height = int(original_image.get_height() * scale_factor)
    scaled_image = pygame.transform.scale(original_image, (new_width, new_height))
    scaled_rect = scaled_image.get_rect(center=(width//2, height//2))

    # Draw everything
    screen.fill((50, 50, 50))  # Dark gray background
    screen.blit(scaled_image, scaled_rect)
    
    # Display scale factor
    font = pygame.font.Font(None, 36)
    text = font.render(f"Scale: {scale_factor:.1f}x", True, (255, 255, 255))
    screen.blit(text, (10, 10))
    
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
print("Scaling demo completed")
Scaling demo completed

Rotating an Image with Mouse Movement

Next, let's implement image rotation using mouse movement. We'll rotate the image based on the mouse position relative to the image center ?

import pygame
import sys
import math

# 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")

# Create a simple colored rectangle as our image
original_image = pygame.Surface((100, 100))
original_image.fill((100, 255, 100))  # Green color
image_center = (width//2, height//2)

# Set up rotation variables
rotation_angle = 0
clock = pygame.time.Clock()

# Game loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEMOTION:
            # Get mouse position
            mouse_x, mouse_y = pygame.mouse.get_pos()
            
            # Calculate angle from image center to mouse
            dx = mouse_x - image_center[0]
            dy = mouse_y - image_center[1]
            rotation_angle = math.degrees(math.atan2(dy, dx))

    # Rotate the image
    rotated_image = pygame.transform.rotate(original_image, -rotation_angle)
    rotated_rect = rotated_image.get_rect(center=image_center)

    # Draw everything
    screen.fill((50, 50, 50))  # Dark gray background
    screen.blit(rotated_image, rotated_rect)
    
    # Draw a line from center to mouse
    pygame.draw.line(screen, (255, 255, 255), image_center, pygame.mouse.get_pos(), 2)
    
    # Display rotation angle
    font = pygame.font.Font(None, 36)
    text = font.render(f"Angle: {rotation_angle:.1f}°", True, (255, 255, 255))
    screen.blit(text, (10, 10))
    
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
print("Rotation demo completed")
Rotation demo completed

Combined Scaling and Rotation

Now let's combine both scaling and rotation functionality into a single interactive demo ?

import pygame
import sys
import math

# 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 Scale and Rotate Demo")

# Create a simple colored rectangle as our image
original_image = pygame.Surface((100, 100))
original_image.fill((100, 100, 255))  # Blue color
image_center = (width//2, height//2)

# Set up transformation variables
scale_factor = 1.0
rotation_angle = 0
clock = pygame.time.Clock()

# Game loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 4:  # Scroll up - scale up
                scale_factor = min(scale_factor + 0.1, 3.0)
            elif event.button == 5:  # Scroll down - scale down
                scale_factor = max(scale_factor - 0.1, 0.1)
        elif event.type == pygame.MOUSEMOTION:
            # Rotate based on mouse position
            mouse_x, mouse_y = pygame.mouse.get_pos()
            dx = mouse_x - image_center[0]
            dy = mouse_y - image_center[1]
            rotation_angle = math.degrees(math.atan2(dy, dx))

    # First scale, then rotate the image
    new_width = int(original_image.get_width() * scale_factor)
    new_height = int(original_image.get_height() * scale_factor)
    scaled_image = pygame.transform.scale(original_image, (new_width, new_height))
    final_image = pygame.transform.rotate(scaled_image, -rotation_angle)
    final_rect = final_image.get_rect(center=image_center)

    # Draw everything
    screen.fill((30, 30, 30))  # Dark background
    screen.blit(final_image, final_rect)
    
    # Draw crosshair at center
    pygame.draw.line(screen, (255, 255, 255), (image_center[0]-20, image_center[1]), 
                     (image_center[0]+20, image_center[1]), 2)
    pygame.draw.line(screen, (255, 255, 255), (image_center[0], image_center[1]-20), 
                     (image_center[0], image_center[1]+20), 2)
    
    # Display transformation info
    font = pygame.font.Font(None, 28)
    scale_text = font.render(f"Scale: {scale_factor:.1f}x", True, (255, 255, 255))
    angle_text = font.render(f"Angle: {rotation_angle:.1f}°", True, (255, 255, 255))
    instructions = font.render("Scroll to scale, move mouse to rotate", True, (200, 200, 200))
    
    screen.blit(scale_text, (10, 10))
    screen.blit(angle_text, (10, 40))
    screen.blit(instructions, (10, height - 30))
    
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
print("Combined transformation demo completed")
Combined transformation demo completed

Key Points

  • Scaling: Use pygame.transform.scale() with mouse scroll events (buttons 4 and 5)
  • Rotation: Use pygame.transform.rotate() with mouse motion events
  • Event Handling: MOUSEBUTTONDOWN for scroll, MOUSEMOTION for mouse movement
  • Performance: Keep the original image and transform it each frame to avoid quality loss
  • Centering: Use get_rect(center=position) to keep transformations centered

Conclusion

Using Pygame's mouse events, you can create interactive image transformations with scaling via scroll wheel and rotation via mouse movement. The key is handling the appropriate events and using pygame.transform functions while maintaining the image center for smooth user experience.

Updated on: 2026-03-27T15:17:50+05:30

843 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements