首页 > 解决方案 > pygame中绘制的图像与给出的位置不匹配

问题描述

大家好,我正在学习pygame的基础知识。我最近遇到了一个问题;我决定加载一个图像并在 pygame 窗口中给它一个随机位置。但问题是有时它不会出现在窗口中。所以我在要加载图像的地方画了一个黑色的指针。然后我发现黑色指针与图像不一致,因此图像没有出现在我想要的位置。所以我想帮助解决这个问题。先感谢您。代码:

import pygame
import random

pygame.init()

#Pygame starters
display_width = 800
display_height = 600
game_display = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Blob runner")
clock = pygame.time.Clock()
targetpng = pygame.image.load("target.png")
#Quit checker
crashed = False
#COLOURS
white = (255, 255, 255)
black = (0, 0, 0)


def draw_environment(x,y):    
    game_display.fill(white)
    #Image
    game_display.blit(targetpng,(x, y)) 
    #Black pointer
    pygame.draw.circle(game_display, black, (x, y), 5 )
    pygame.display.update()

x, y = random.randrange(0,display_width), random.randrange(0,display_height)

while not crashed:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
        # print(event)

    draw_environment(x,y)
    clock.tick(30)

pygame.quit()
quit()

图片:在此处输入图像描述

标签: pythonimagepygamedrawblit

解决方案


图像有大小。图像可能会出现在右侧或底部的窗口之外。的原点blit将图像的左上角放置到指定位置。

如果您希望图像以(x, y)为中心,则必须获取pygame.Rect图像大小 ( get_rect) 并将矩形的中心设置为指定位置(关键字参数)。使用矩形指定blit操作的位置。

img_rect = targetpng.get_rect(center = (x, y))
game_display.blit(targetpng, img_rect) 

图像具有大小,因此图像的随机位置必须在[image_size/2, window_sizw - image_size/2]范围内。
a 的宽度和高度pygame.Surface可以通过get_width()/get_height()或获得get_size()。例如:

img_size = targetpng.get_size()
x = random.randrange(img_size[0]//2, display_width  - img_size[0]//2)
y = random.randrange(img_size[1]//2, display_height - img_size[1]//2)

推荐阅读