PyGame - How to get an image in the center of the screen

后端 未结 2 516
深忆病人
深忆病人 2021-01-29 00:25
# MENU
def gameMenu():
intro = True
while(intro == True):
    win.fill((0,0,0))
    iPATH = f\"{PATH}/assets/textures/titleScreen/buttons\"
    win.blit(pygame.image.loa         


        
相关标签:
2条回答
  • 2021-01-29 01:00

    You made a simple mathematical mistake. If your screen size is 800 and you divide it by 2, you obtain 400. Therefore, with an image width of, say, 100 pixels, you'll be covering pixels 400 to 500, thus having an skew towards the right.

    If you want to truly center your image, you need to account for half its width. Therefore, you calculation to obtain the top left x coordinate should look like:

    x_centered = screen_width / 2 - image_width / 2
    y_centered = screen_height / 2 - image_height / 2 #similarly..
    

    Adapting to the specifics of your current project should be rather straightforward.

    0 讨论(0)
  • 2021-01-29 01:18

    First of all, by convention, you should name your screen Surface simply screen.

    Then, you're loading the image files over and over again in the while loop. Just load it once.

    It's also good to (almost) always use convert after loading an image so the Surface will have the same pixel format as the screen.

    Finally, in pygame, you should use the Rect class for (almost) everything related to drawing/positioning.

    Here you can see how easy it is to center something using the Rect class. I also reordered your loop to follow the classic input/update/draw convention and removed the second image for brevity:

    def gameMenu():
    
        iPATH = f"{PATH}/assets/textures/titleScreen/buttons"
        logo = pygame.image.load(os.path.join(f"{iPATH}/Logo.png")).convert()
    
        logo_rect = logo.get_rect(center = screen.get_rect().center)
    
        while True:
    
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
    
            keys = pygame.key.get_pressed()
            if keys[selectButton]:
                print("clicked z")
                break
            elif keys[backButton]:
                print("clicked x")
    
            screen.fill((0,0,0))
            screen.blit(logo, logo_rect)
            pygame.display.update()
    
    0 讨论(0)
提交回复
热议问题