简体   繁体   English

如何在 pygame 中的坐标上居中图像

[英]How To Center An Image on Coordinates in pygame

I'm trying to display a custom png file in a pygame screen, but when I call我正在尝试在 pygame 屏幕中显示自定义 png 文件,但是当我调用

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 stackoverflow answer, but it didn't change my image position: How to centre an image in pygame?已经引用了以下 stackoverflow 答案,但它并没有改变我的图像 position: How to center an image in pygame?

See How to center an image in the middle of the window in pygame?请参阅如何在 pygame 的 window 中间将图像居中? . . 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM