So I am Loading an Image in python and I need to Center the Image in Pygame. As Pygame starts the drawing from the upper left side of the screen so the x and y coordinates 0,0 doesn't work. Can anyone tell me the center x and y coordinates of the pygame window?
CodePudding user response:
You can get the center of the window through the window rectangle (pygame.Surface.get_rect
):
screen = pygame.display.set_mode((800, 600))
center = screen.get_rect().center
Use this to blit
an image
(pygame.Surface
object) in the center of the screen:
screen.blit(image, image.get_rect(center = screen.get_rect().center))
pygame.Surface.get_rect()
returns a rectangle with the size of the Surface object, that always starts at (0, 0). However, the position of the rectangle can be specified with a keyword argument. In this case, the center of the rectangle is set by the center of the screen.
When the 2nd argument of blit
is a rectangle (pygame.Rect
), the upper left corner of the rectangle will be used as the position for the blit
.