Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

center images and add padding according to screen resolution

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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()

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading