3

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?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • Can you share the image? Is the image just much bigger than the arrow and the arrow is only drawn in the top right of the image? – Rabbid76 Dec 18 '20 at 18:10

2 Answers2

4

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()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
0

I have the same problem, and I think because of this line:

image = pygame.transform.scale(image, (x, y))

After scaling the image in gimp, everything is working as intended.

F3KDOM
  • 21
  • 1