How to get the correct dimensions for a pygame rectangle created from an image

pygame.Surface.get_rect.get_rect() returns a rectangle with the size of the Surface object. This function does not consider the drawing area in the image. You can find the bounding rectangle of the painted area in the surface, with pygame.Surface.get_bounding_rect:

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

See the example. The black rectangle is the Surface rectangle and the red rectangle is the union of the mask component rectangles:

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()

Leave a Comment