How can I crop an image with Pygame?
Asked Answered
S

4

26

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?

Substantialism answered 4/6, 2011 at 22:28 Comment(0)
K
47
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.

Kimono answered 4/6, 2011 at 23:50 Comment(0)
A
8

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))
Apache answered 14/6, 2018 at 15:5 Comment(0)
S
4

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)
target.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)
target.blit(cropped_subsurf, (posx, posy))
Sphygmograph answered 8/1, 2021 at 11:2 Comment(0)
O
-2

I think the best way to do it is crop the image of these 3 kind of buttons in a external program and load in different surface instead use pygame to crop it

Oreopithecus answered 30/8, 2017 at 23:17 Comment(2)
Maybe that is a better idea, but that doesn't answer the question.Collegium
Remember that other people in the future will read the same answers to these questions. Even if the answer is not optimal for the question asker's use case, it may be for others.Bassinet

© 2022 - 2024 — McMap. All rights reserved.