2

I'm trying to make a game using pygame but I came up with an issue of people getting annoyed of the resolution they're working with, and can't resize window without stretching it.

Here is an example picture of what I'm trying to achieve.

Example Picture of window with black sides as the game ratio is still the same even when stretched

here's what I tried.

window.blit(pg.transform.scale(screen, (window.get_size())), (0, 0)) # The game screen stretching

PS: It's hard to explain so I had to show an image

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
AidanGamin
  • 67
  • 1
  • 7

1 Answers1

3

Use the following algortihm:

  1. Get the bounding rectangle of the image and set the center of the rectangle to the center of the destination rectangle.
  2. Use pygame.Rect.fit() to resize and move the aspect ratio rectangle into the destination rectangle.
  3. Use the size of the new rectangle to scale the image.
  4. blit the image at the position of the rectangle.
def blit_fit(dest_surf, image, dest_rect):
    image_rect = image.get_rect(center = dest_rect.center)
    fit_rect = image_rect.fit(dest_rect)
    scaled_image = pygame.transform.scale(image, fit_rect.size) 
    dest_surf.blit(scaled_image, fit_rect)

Minimal example:

import pygame

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

font = pygame.font.SysFont(None, 100)
image = font.render("Screen", True, (255, 255, 0))
pygame.draw.rect(image, (255, 255, 255), image.get_rect(), 1)

def blit_fit(dest_surf, image, dest_rect):
    image_rect = image.get_rect(center = dest_rect.center)
    fit_rect = image_rect.fit(dest_rect)
    scaled_image = pygame.transform.scale(image, fit_rect.size) 
    dest_surf.blit(scaled_image, fit_rect) 

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

    window.fill(0)
    blit_fit(window, image, window.get_rect())    
    pygame.display.flip()
    clock.tick(100)

pygame.quit()
exit()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174