PyGameExamplesAndAnswers

StackOverflow            reply.it reply.it

“The only way to go fast, is to go well.”
Robert C. Martin, Clean Architecture


Mask

Create mask from Surface

Related Stack Overflow questions:

Mask collision

Related Stack Overflow questions:

Mask count pixel

Related Stack Overflow questions:

Selection and highlighting

Related Stack Overflow questions:

Circular mask

Related Stack Overflow questions:

Mask overlapping area

Related Stack Overflow questions:

Mask bounding area rectangle

Related Stack Overflow questions:

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. If you want to find the bounding rectangle of the painted area in the surface, you need to create a mask.

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:

surf_mask = pygame.mask.from_surface(surf)

Get a list containing a bounding rectangles (sequence of pygame.Rect objects) for each connected component with get_bounding_rects.
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:

rect_list = surf_mask.get_bounding_rects()

Create the union rectangle of the sequence of rectangles with unionall:

surf_mask_rect = rect_list[0].unionall(rect_list)
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

Sprite mask

See Sprite, Group and Sprite mask - Sprite mask