Table of contents
1.
Introduction
2.
Transformation Of an Image in Pygame
3.
Frequently Asked Questions
3.1.
What is Pygame?
3.2.
How to rotate an image in Pygame?
3.3.
How to scale an image in Pygame?
3.4.
How does Pygame handle negative angle amounts?
3.5.
How to transform the image using the mouse in Pygame?
4.
Conclusion
Last Updated: Mar 27, 2024

Using the mouse to scale and rotate an image in PyGame

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Pygame library is one of the python programming libraries with very efficient functionalities such as building custom events, taking input from the user through the keyboard, creating custom input boxes for taking inputs, etc. This article will discuss how to use the mouse to scale and rotate (to transform) an image in Pygame. I hope you will enjoy the article!

Transformation Of an Image in Pygame

To transform an image, we have two cases: to scale and rotate an image. To scale an image: we need to know at what ratio the image needs to be increased or decreased. And to rotate an image, we need to know at what angle the image needs to be rotated. For these transformations, we need to know the current coordinates of an image. The following functions and properties will help us to transform an image.

- > event.pos:  to get the current position.

- > math.degrees: to calculate and get the angle in degrees.

- >pygame.transform.rotozoom(): We can calculate the updated position of the image using the rotozoom function, which is a combined scale and rotation transform.

The process of transforming an image is simple. We need to create a rectangle box around our image, and at first, we need to fetch the current position, and then we need to set what happens when the game is in a running state. We will take a look at the code below.
Pygame application code to demonstrate the transformation of an image:

import pygame
import math
from pygame.locals import *

# Set the colors
RED = (255, 0, 0)
BLACK = (0, 0, 0)
YELLOW = (255, 255, 0)

#intialize the pygamem constructor
pygame.init()

#Set dimensions of screen
w, h = 600, 440
screen = pygame.display.set_mode((w, h))

# Set the intial running, angle and scale values
running = True
angle = 0
scale = 1

# Set a sample image
img_logo = pygame.image.load('Login_page.png')
img_logo.convert()

# Draw a rectangle around the image using get_rect()
rect_logo = img_logo.get_rect()
pygame.draw.rect(img_logo, RED, rect_logo, 1)

# Set the current center and mouse position
center = w//2, h//2
mouse = pygame.mouse.get_pos()
img = img_logo
rect = img.get_rect()
rect.center = center

# we need to set what happens when game is in running state
while running:
	for event in pygame.event.get():

		# Close if the user quits the game
		if event.type == QUIT:
			running = False

		# Dealing with the angle part
		if event.type == KEYDOWN:
			if event.key == K_ra:
				if event.mod & KMOD_SHIFT:
					angle -= 5
				else:
					angle += 5

			# Dealing with the scaling part
			elif event.key == K_sa:
				if event.mod & KMOD_SHIFT:
					scale /= 1.5
				else:
					scale *= 1.5
				
		# Move the image with the modified coordinates,
		# angle and scale		
		elif event.type == MOUSEMOTION:
			mouse = event.pos
			xi = mouse[0] - center[0]
			yi = mouse[1] - center[1]
			d = math.sqrt(xi ** 2 + yi ** 2)
			angle = math.degrees(-math.atan2(yi, xi))
			scale = abs(5 * d / w)
			img = pygame.transform.rotozoom(img_logo, angle, scale)
			rect = img.get_rect()
			rect.center = center
	
	# Set screen color and image on screen
	screen.fill(YELLOW)
	screen.blit(img, rect)

	# Draw the rectangle, line and circle through which image can be transformed
	pygame.draw.rect(screen, BLACK, rect, 3)
	pygame.draw.line(screen, RED, center, mouse, 2)
	pygame.draw.circle(screen, RED, center, 6, 1)
	pygame.draw.circle(screen, BLACK, mouse, 6, 2)
	
	# Updating the pygame application
	pygame.display.update()

# Quit the GUI game
pygame.quit()
You can also try this code with Online Python Compiler
Run Code

You can have a try on running the above pygame program to taste how to use the mouse pointers to scale and rotate an image in pygame. You can refer gfg blog for more information.

Also See, Image Sampling 

Frequently Asked Questions

What is Pygame?

Pygame is a python programming language library that allows developers to develop applications on gaming themes. It is a well-developed library that has many useful functions to implement several functionalities of our application.

How to rotate an image in Pygame?

We can use the pygame built-in method called pygame.transform.rotate(your_image, degrees_to_be_rotated), for which we need to pass an image that is to be rotated and the degrees by which the image needs to be rotated. In the above example, we did the same.

How to scale an image in Pygame?

In pygame, we can use pygame.transform.scale(image_to_be_scaled, DEFAULT_IMAGE_SIZE) method for which we need to pass the image that is to be scaled and the initial default image size when the image is not scaled.

How does Pygame handle negative angle amounts?

Since we know that a positive angle means it will rotate anticlockwise, and similarly, negative angle amounts will rotate clockwise. Pygame will generally pick a color that matches the surface color key or the top-left pixel value to handle the negative angle amounts.

How to transform the image using the mouse in Pygame?

The transformation of an image involves either of the tasks called scaling an image and as well as rotating an image. So to scale the image, we can use the pygame.transform.scale() method, and to rotate an image, we can use the pygame.transform.rotate() method as discussed in the article.

Conclusion

In this current article, we have extensively discussed how to use the mouse to rotate an image and as well as scaling an image. After reading this article, are you not feeling excited to read/explore more articles on the topic of Pygame? Don't worry; Coding Ninjas has you covered. 
You can refer to our Guided Paths on Coding Ninjas Studio to upskill your skills in Data Structures and AlgorithmsJavaScriptSystem DesignCompetitive Programming, and many more! If you really want to test your competency in coding, you may check out the  contests and participate in the mock test series hosted on Coding Ninjas Studio! But suppose you have just started your learning process and are looking for the most important questions asked by tech giants like Microsoft, Amazon, Uber, etc. In that case, you must also look at the problemsinterview experiences, and interview bundle for placement preparations. Nevertheless, you may also consider our paid courses to give your career an edge over others! Do upvote our exciting blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass