How can I crop an image with Pygame?

I am learning pygame and want a graphic for a button with the three states: normal, hover, and pressed. I have an image like this one ...

Three button states, stacked vertically

... and I want to get a new Surface using a portion of it.

I'm loading the image with this code:

 buttonStates = pygame.image.load(os.path.join('image','button.png'))

How can I make a new surface using just a portion of that graphic?


Solution 1:

cropped = pygame.Surface((80, 80))
cropped.blit(buttonStates, (0, 0), (30, 30, 80, 80))

The blit method on a surface 'pastes' another surface on to it. The first argument to blit is the source surface. The second is the location to paste to (in this case, the top left corner). The third (optional) argument is the area of the source image to paste from -- in this case an 80x80 square 30px from the top and 30px from the left.

Solution 2:

You can also use the pygame.Surface.subsurface method to create subsurfaces that share their pixels with their parent surface. However, you have to make sure that the rect is inside of the image area or a ValueError: subsurface rectangle outside surface area will be raised.

subsurface = a_surface.subsurface((x, y, width, height))

Solution 3:

There are 2 possibilities.

The blit method allows to specify a rectangular sub-area of the source _Surface:

[...] An optional area rectangle can be passed as well. This represents a smaller portion of the source Surface to draw. [...]

In this way you can blit an area of the source surface directly onto a target:

cropped_region = (x, y, width, height)
traget.blit(source_surf, (posx, posy), cropped_region)

Alternatively, you can define a subsurface that is directly linked to the source surface with the subsurface method:

Returns a new Surface that shares its pixels with its new parent. The new Surface is considered a child of the original. Modifications to either Surface pixels will effect each other.

As soon as a subsurface has been created, it can be used as a normal surface at any time:

cropped_region = (x, y, width, height)
cropped_subsurf = source_surf.subsurface(cropped_region)
traget.blit(cropped_subsurf, (posx, posy))