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
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()
If you scale 1600x900 to 1280x720 you have
scale_x = 1280.0/1600
scale_y = 720.0/900
Than you can use it to find button size, and button position
button_width = 300 * scale_x
button_height = 300 * scale_y
button_x = 1440 * scale_x
button_y = 860 * scale_y
If you scale 1280x720 to 1600x900 you have
scale_x = 1600.0/1280
scale_y = 900.0/720
and rest is the same.
I add .0
to value to make float
- otherwise scale_x
, scale_y
will be rounded to integer
- in this example to 0
(zero) (Python 2.x)