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

I have created an image's rectangle of a sprite using the command, pygame.image.get_rect(). When locating coordinates of key points on the rectangle such as bottomleft by drawing dots, I see that the rectangle's dimensions are completely different to the image's dimensions. In this case, the image is just the arrow head. The top right coordinate of the rectangle is correct, however the bottom left coordinate isn't.

Test to see rectangle

code to draw dots:

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

How can I resize the rectangle so that it fits the image?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1