gpt4 book ai didi

python - 如何获得从图像创建的 pygame 矩形的正确尺寸

转载 作者:行者123 更新时间:2023-12-05 02:46:42 26 4
gpt4 key购买 nike

我使用命令 pygame.image.get_rect() 创建了 Sprite 图像的矩形。当通过绘制点定位矩形上的关键点坐标时,例如 bottomleft,我看到矩形的尺寸与图像的尺寸完全不同。在这种情况下,图像只是箭头。矩形的右上坐标正确,但左下坐标不正确。

Test to see rectangle

绘制点的代码:

pygame.draw.circle(simulation_screen, red, velocity_arrow.rect.topright, 2)
pygame.draw.circle(simulation_screen,red,velocity_arrow.rect.bottomleft,2)

如何调整矩形以适合图像?

最佳答案

pygame.Surface.get_rect.get_rect()返回具有 Surface 对象大小的矩形。此功能不考虑图像中的绘图区域。你可以在表面找到绘制区域的边界矩形,用pygame.Surface.get_bounding_rect :

bounding_rect = image.get_bounding_rect()
bounding_rect.move_ip(target_rect.topleft)

参见示例。黑色矩形是 Surface 矩形,红色矩形是 mask 组件矩形的并集:

repl.it/@Rabbid76/ImageHitbox

import pygame

pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

try:
my_image = pygame.image.load('icon/Bomb-256.png')
except:
my_image = pygame.Surface((200, 200), pygame.SRCALPHA)
pygame.draw.circle(my_image, (0, 128, 0), (60, 60), 40)
pygame.draw.circle(my_image, (0, 0, 128), (100, 150), 40)

run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False

pos = window.get_rect().center
my_image_rect = my_image.get_rect(center = pos)
bounding_rect = my_image.get_bounding_rect()
bounding_rect.move_ip(my_image_rect.topleft)

window.fill((255, 255, 255))
window.blit(my_image, my_image_rect)
pygame.draw.rect(window, (0, 0, 0), my_image_rect, 3)
pygame.draw.rect(window, (255, 0, 0), bounding_rect, 3)
pygame.display.flip()

pygame.quit()
exit()

关于python - 如何获得从图像创建的 pygame 矩形的正确尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65361582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com