问题
I'm having troubles getting the center of surfaces with pygame. It defaults to the upper left corner of surfaces when trying to place them on other surfaces.
To demonstrate what I mean I wrote a short program.
import pygame
WHITE = (255, 255, 255)
pygame.init()
#creating a test screen
screen = pygame.display.set_mode((500, 500), pygame.RESIZABLE)
#creating the canvas
game_canvas = screen.copy()
game_canvas.fill(WHITE)
#drawing the canvas onto screen with coords 50, 50 (tho its using the upper left of game_canvas)
screen.blit(pygame.transform.scale(game_canvas, (200, 200)), (50, 50))
pygame.display.flip()
#you can ignore this part.. just making the program not freeze on you if you try to run it
import sys
clock = pygame.time.Clock()
while True:
delta_time = clock.tick(60) / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
If you run this program it will draw a 200 by 200 white game_canvas on the screen (display) at the coords 50, 50. But instead of using the center of the game_canvas at the coords 50, 50.. the upper left is at 50, 50.
So how do I use the center of the game_canvas to have it place at the coords 50, 50 or any other given coords?
回答1:
It will always blit the Surface at the topleft corner. A way around this is to calculate where you have to place the Surface in order for it to be centered around a position.
x, y = 50, 50
screen.blit(surface, (x - surface.get_width() // 2, y - surface.get_height() // 2 ))
This will position it's center at the (x, y) coordinates.
来源:https://stackoverflow.com/questions/40953796/getting-the-center-of-surfaces-in-pygame-with-python-3-4