center images and add padding according to screen resolution

Question:

I’m using pygame to show two images: I’ve maneged to resize the images according to the screen size of my user. But I’d like to standardized also the x and the y coordination position of my images. The images should always be in the middle according to the y axis and have the a little bit of pad to stay close to the border of the monitor like this no matter what resolution my user
has:

enter image description here

This are the values that I’d like to standardized

    WIN.blit(FIRST_IMG, (100, 280))

    WIN.blit(SECOND_IMAGE, (1350, 280))

This is my code right now:

import pygame
import os


WIN = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)

WHITE = (255, 255, 255)

FPS = 60

SCREEN_INFO = pygame.display.Info()

IMAGE_WIDTH, IMG_HEIGHT = SCREEN_INFO.current_w // 5, SCREEN_INFO.current_h // 3

FIRST_IMG = pygame.image.load(os.path.join("Assets", "7.png"))
FIRST_IMG = pygame.transform.scale(FIRST_IMG, (IMAGE_WIDTH, IMG_HEIGHT))

SECOND_IMAGE = pygame.image.load(os.path.join("Assets", "8.png"))
SECOND_IMAGE = pygame.transform.scale(SECOND_IMAGE, (IMAGE_WIDTH, IMG_HEIGHT))


def draw_window():
    WIN.fill(WHITE)

    WIN.blit(FIRST_IMG, (100, 280))

    WIN.blit(SECOND_IMAGE, (1350, 280))

    pygame.display.update()


def main():
    clock = pygame.time.Clock()
    run = True

    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    run = False

        draw_window()

    pygame.quit()


if __name__ == "__main__":
    main()
Asked By: Diana Mele

||

Answers:

Get the bounding rectangle of the image and set the centery and left or right of the rectangle depending on the size of WIN. Use the rectangles to blit the images:

def draw_window():
    width, height = WIN.get_size()

    WIN.fill(WHITE)

    first_rect = FIRST_IMG.get_rect(midleft = (100, height // 2))
    WIN.blit(FIRST_IMG, first_rect)

    second_rect = FIRST_IMG.get_rect(midright = (width - 100, height // 2))
    WIN.blit(SECOND_IMAGE, second_rect)

    pygame.display.update()
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.