Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I crop an image with Pygame?

Tags:

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?

like image 953
dobleseis Avatar asked Jun 04 '11 22:06

dobleseis


People also ask

How do you crop a surface in Pygame?

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.

How do you half the size of an image in pygame?

To scale the image we use the pygame. transform. scale(image, DEFAULT_IMAGE_SIZE) method where we pass the image that we are going to scale and the default image size that we will set manually according to our need.


2 Answers

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.

like image 170
PAG Avatar answered Sep 21 '22 02:09

PAG


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)) 
like image 39
skrx Avatar answered Sep 21 '22 02:09

skrx