How to scale an image by window size?

Viewed 131

I have a square, non-resizable, pygame window and the size of it is calculated by monitor size. I have images that aren't square that I want created scaled by window size. I want it to be scaled by my SCREEN_SIZE variable. Here is my code, it puts an image up in the middle of the screen, but if you change your resolution the image stays the same size:

import pygame

pygame.init()

# Sets screen size by using your monitors resolution
SCREEN_SIZE = pygame.display.Info().current_h/1.65 

screen = pygame.display.set_mode((int(SCREEN_SIZE), int(SCREEN_SIZE)))

gameRunning = True

""" This is the part I need help with. When I run my program the image is the correct 
size, but when I change my resolution the image stays the same size and the window's 
size changes. I need the image to proportionally scale with the window. """
imgSize = 0.2
img = pygame.image.load(r"location of an image on your PC")
img = pygame.transform.smoothscale(img, (int(img.get_width() * imgSize), int(img.get_height() * imgSize))) 

rect = img.get_rect()
rect.center = (screen.get_width()/2, screen.get_height()/2)

while gameRunning == True:
    pygame.display.update()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameRunning = False
            pygame.quit()
            break

    screen.fill((255,255,255))



    screen.blit(img, rect)

For the code to work you will need to sub in an image location for the "img" variable and mess with the imgSize variable.

1 Answers

Compare the ration of the width and the ratio of the height. Scale the image by the minimum ratio. This works even with non-square window resolutions.

ratio_x = screen.get_width() / img.get_width()
ratio_y = screen.get_height() / img.get_height()
scale = min(ratio_x, ratio_y)
img = pygame.transform.smoothscale(img, (int(img.get_width() * scale), int(img.get_height() * scale))) 

Minimal example:

import pygame

pygame.init()

screen = pygame.display.set_mode((300, 300))

img = pygame.image.load(r"parrot1.png")
scale = min(screen.get_width() / img.get_width(), screen.get_height() / img.get_height())
img = pygame.transform.smoothscale(img, 
          (round(img.get_width() * scale), round(img.get_height() * scale))) 

rect = img.get_rect(center = screen.get_rect().center)

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

    screen.fill((127,127,127))
    screen.blit(img, rect)
    pygame.display.flip()

pygame.quit()
exit()
Related