Scaling the background to the size of the window can easily be done with pygame.transform.scale()
lor smoothscale
. e.g.:
import pygame
pygame.init()
window = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
background = pygame.image.load('sky.png').convert()
background = pygame.transform.smoothscale(background, window.get_size())
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.blit(background, (0, 0))
pygame.display.flip()
pygame.quit()
exit()
However, this does not take into account the aspect ratio of the background. To fit the window into the background, you need to compare the width and height ratio and scale the image by the minimum ratio.
The following function scales an image to the desired size, but retains the aspect ratio. The function returns the scaled image and a rectangle indicating the position of the scaled image in the center of the area:
def transformScaleKeepRatio(image, size):
iwidth, iheight = image.get_size()
scale = min(size[0] / iwidth, size[1] / iheight)
new_size = (round(iwidth * scale), round(iheight * scale))
scaled_image = pygame.transform.smoothscale(image, new_size)
image_rect = scaled_image.get_rect(center = (size[0] // 2, size[1] // 2))
return scaled_image, image_rect
If you want to fill the entire window with the background, keeping the aspect ratio but cropping the sides of the background, just replace min
with max
.
scale = min(size[0] / iwidth, size[1] / iheight)
scale = max(size[0] / iwidth, size[1] / iheight)
Minimal example
import pygame
def transformScaleKeepRatio(image, size):
iwidth, iheight = image.get_size()
scale = min(size[0] / iwidth, size[1] / iheight)
#scale = max(size[0] / iwidth, size[1] / iheight)
new_size = (round(iwidth * scale), round(iheight * scale))
scaled_image = pygame.transform.smoothscale(image, new_size)
image_rect = scaled_image.get_rect(center = (size[0] // 2, size[1] // 2))
return scaled_image, image_rect
pygame.init()
window = pygame.display.set_mode((300, 300), pygame.RESIZABLE)
clock = pygame.time.Clock()
background = pygame.image.load('parrot.png').convert_alpha()
scaled_bg, bg_rect = transformScaleKeepRatio(background, window.get_size())
run = True
while run == True:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.VIDEORESIZE:
window = pygame.display.set_mode(event.size, pygame.RESIZABLE)
scaled_bg, bg_rect = transformScaleKeepRatio(background, window.get_size())
window.fill((127, 127, 127))
window.blit(scaled_bg, bg_rect)
pygame.display.flip()
pygame.quit()
exit()