4

How do you change the size of a surface in pygame that has an image (not scaling). When I load an image in pygame the surface becomes the size of the image. I need to change the size of the surface to be the size of a frame (sprite sheet).

Here is code I used to solve issue (thanks to Chris Dennett):

self.surface = pygame.Surface((20, 20))
self.surface.blit(pygame.image.load(imageName).convert_alpha(), (0,0), (0, 0, frameWidth, frameHeight))
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
nobody
  • 161
  • 1
  • 4
  • 8
  • 2
    Not really, I'll answer. – Chris Dennett Jun 26 '11 at 21:20
  • The [surface docs](http://pygame.org/docs/ref/surface.html) mention a constructor that takes both a size, and another surface: `pygame.Surface((width, height), flags=0, Surface): return Surface`. But it is not clear on whether it copies that surface, or just copies the _attributes_ of that surface. – Merlyn Morgan-Graham Jun 26 '11 at 21:26
  • 1
    Yeah, I looked at that. I'm not sure it'd work in this case. I think it just copies the surface attributes, so might be useful in maintaining the same colour depth / pixel format and so on. – Chris Dennett Jun 26 '11 at 21:28

2 Answers2

5

For sprite sheets, you have 2 good options.

1) Load spritesheet as one Surface.

When blitting, use the source rect argument. This will blit just one frame, from the sheet.

2) Use subsurfaces.

Load spritesheet as one Surface. Load a subsurface, of each frame you want : http://www.pygame.org/docs/ref/surface.html#Surface.subsurface

As far as you are concerned, the subsurface is a 'new' surface, with the width and height of the cell. But, it's not duplicate memory. It's linked.

From the docs:

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. Surface information like clipping area and color keys are unique to each Surface.

Community
  • 1
  • 1
ninMonkey
  • 7,211
  • 8
  • 37
  • 66
3

Create a new surface, passing in the desired width and height as arguments (i.e., how big the sprite is). Then use newsurf.blit(spritesheet, (0, 0), (posX, posY, newsurf.getWidth(), newsurf.getHeight())). Should work. Then you can use newsurf as your sprite. posX and posY should be the x and y you want to blit from in your sprite sheet respectively.

Chris Dennett
  • 22,412
  • 8
  • 58
  • 84
  • 1
    problem solved. Thanks a bunch: self.surface.blit(pygame.image.load(imageName).convert_alpha(), (0,0), (0, 0, frameWidth, frameHeight)) – nobody Jun 26 '11 at 22:01
  • Oh, you want to avoid loading the sprite sheet over and over. It's really inefficient :) – Chris Dennett Jun 26 '11 at 22:21