Skip to content Skip to sidebar Skip to footer

Questions Regarding The Pygame.mask Function

So I read the documentation of pygame but I could not understand it clearly. I recently asked a question about bitmap fonts and I got some code as my answer; here is the code: impo

Solution 1:

pygame.mask.from_surface creates a pygame.mask.Mask object form a pygame.Surface. A Surface is bitmap. A Mask is an 2 dimensional array with Boolean values. The Mask created is the size of the _Surface. A field is True if the corresponding pixel in the surface is not transparent, and False if it is transparent.

pygame.mask.Mask.get_bounding_rects creates a list of pygame.Rect objects. Each rectangle describes a bounding area of connected pixles. If the Surface contains exactly 1 connected image, you will get exactly 1 rectangle surrounding the image.


See the example. The black rectangle is the Surface rectangle and the red rectangle is the bound rectangle of the connected component:

repl.it/@Rabbid76/ImageHitbox

import pygame

defgetMaskRect(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 = Truewhile 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()

Post a Comment for "Questions Regarding The Pygame.mask Function"