How to scale images to screen size in Pygame

Ilmiont picture Ilmiont · Nov 15, 2013 · Viewed 104.3k times · Source

I was wondering how I would go about scaling the size of images in pygame projects to the resolution of the screen. For example, envisage the following scenario assuming windowed display mode for the time being; I assume full screen will be the same:

  • I have a 1600x900 background image which of course displays natively in a 1600x900 window

  • In a 1280x720 window I can obviously just scale this images' rect to 1280x720

  • What happens, however if I need to add, say a 300x300 px image at x,y 1440,860 (example sizes) that is sized to fit with the original 1600x900 background? Of course for the 1600x900 I can of course use the image natively but what about the smaller/larger window sizes?

Basically, how do I scale images to the window size and then position them accordingly? I guess there must be a REALLY easy automated method but right now I can't figure it out and quite frankly haven't got time to search for it...

Thanks in advance, Ilmiont

Answer

unutbu picture unutbu · Nov 15, 2013

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

You can then get the bounding rectangle of picture with

rect = picture.get_rect()

and move the picture with

rect = rect.move((x, y))
screen.blit(picture, rect)

where screen was set with something like

screen = pygame.display.set_mode((1600, 900))

To allow your widgets to adjust to various screen sizes, you could make the display resizable:

import os
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT:
        pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(
            event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
        pygame.display.flip()