【问题标题】:How to get the correct dimensions for a pygame rectangle created from an image如何获得从图像创建的 pygame 矩形的正确尺寸
【发布时间】:2021-03-29 09:01:16
【问题描述】:

我使用命令pygame.image.get_rect() 创建了一个精灵的图像矩形。当通过绘制点定位矩形上的关键点坐标时,例如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)

如何调整矩形的大小以使其适合图像?

【问题讨论】:

  • 可以分享图片吗?图片是不是比箭头大很多,箭头只画在图片的右上角?

标签: python pygame pygame-surface


【解决方案1】:

pygame.Surface.get_rect.get_rect() 返回一个与 Surface 对象大小相同的矩形。此函数不考虑图像中的绘图区域。如果要在表面中找到绘制区域的边界矩形,则需要创建一个遮罩。

pygame.mask.from_surfacepygame.Surface 创建一个pygame.mask.Mask 对象。
Surface 是位图。 Mask 是一个具有Boolean 值的二维数组。创建的Mask 是_Surface 的大小。如果表面中对应的像素不透明,则字段为True,如果透明,则为False

surf_mask = pygame.mask.from_surface(surf)

为每个使用get_bounding_rects 连接的组件获取一个包含边界矩形(pygame.Rect 对象序列)的列表。
pygame.mask.Mask.get_bounding_rects 创建一个pygame.Rect 对象列表。每个矩形描述了连接像素的边界区域。如果 Surface 恰好包含 1 个连接的图像,则您将得到 1 个围绕图像的矩形:

rect_list = surf_mask.get_bounding_rects()

unionall创建矩形序列的联合矩形:

surf_mask_rect = rect_list[0].unionall(rect_list)

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

repl.it/@Rabbid76/ImageHitbox

import pygame

def getMaskRect(surf, top = 0, left = 0):
    surf_mask = pygame.mask.from_surface(surf)
    rect_list = surf_mask.get_bounding_rects()
    surf_mask_rect = rect_list[0].unionall(rect_list)
    surf_mask_rect.move_ip(top, left)
    return surf_mask_rect

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

try:
    my_image = pygame.image.load('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)
    my_image_mask_rect = getMaskRect(my_image, *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), my_image_mask_rect, 3)
    pygame.display.flip()

pygame.quit()
exit()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多