Search code examples
pythonpygame

How to center an image in Pygame?


I'm trying to display a custom png file in a pygame screen, but when I call...

screen.blit(image, screen.get_rect().center)

...it centers the image's upper left corner on the coordinates.

How can I fix this so that the center of the image is on the coordinates? Already referenced the following answer, but it didn't change my image position: How to centre an image in pygame?


Solution

  • See How to center an image in the middle of the window in pygame?. If you want to center the image in the middle of the screen, you need to get the bounding rectangle of the image and set the center of the rectangle to the center of the screen:

    screen.blit(image, screen.get_rect().center)

    screen.blit(image, image.get_rect(center = screen.get_rect().center))
    

    The same in single steps:

    screen_rect = screen.get_rect()
    screen_center = screen_rect.center
    image_rect = image.get_rect()
    image_rect.center = screen_center 
    screen.blit(image, image_rect)
    

    Minimal example:

    import pygame
    
    pygame.init()
    screen = pygame.display.set_mode((400, 400))
    clock = pygame.time.Clock()
    
    image = pygame.image.load("image.png")
    
    run = True
    while run:
        clock.tick(100)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False 
    
        screen.fill(0)
        screen.blit(image, image.get_rect(center = screen.get_rect().center))
        pygame.display.flip()
    
    pygame.quit()
    exit()