Permalink
Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
92 lines (77 sloc) 2.62 KB
import pygame
import Image
class Animation():
'''
Support for animated images in pygame.
'''
def __init__(self, path, mode = 'RGB', play_once = False, colorkey = None):
self.data = Image.open(path)
self.size = self.data.size
self.mode = mode
self.play_once = play_once
self.colorkey = (0, 0, 0) # Dummy
self.rewind() # Just getting the first frame
if colorkey:
self.colorkey = colorkey
else:
self.colorkey = self.frame.get_at((0, 0))
self.rewind()
def _update(self):
frame = self.data.convert(self.mode).tostring()
self.frame = pygame.image.frombuffer(frame, self.size, self.mode)
self.frame.set_colorkey(self.colorkey)
def next(self):
'''
Jumps to next frame.
Rewinds back to first frame when done. Set GifViewer.play_once to True
to make it stop.
'''
try:
self.data.seek(self.data.tell() + 1)
except EOFError: # End of file, this was the last frame
if self.play_once:
raise
else:
self.rewind()
self._update()
return self.frame
def rewind(self):
'''Rewinds back to frame 0'''
self.data.seek(0)
self._update()
def getFrameNumber(self):
'''Returns the current frame number'''
self.data.tell()
def getFrame(self):
'''Returns the surface of the current frame'''
return self.frame
if __name__ == '__main__':
'''
A simple usage example, first asks for a gif file and runs it in infinitely.
Holding any key will pause the animation.
Pressing a mouse button will restart the animation.
'''
from pygame.locals import *
from sys import exit
pygame.init()
gif = Animation(raw_input('Enter path to the image: '))
screen = pygame.display.set_mode((100, 100))
clock = pygame.time.Clock()
animating = True
print "Okey, everything goes well, let's take a look..."
while True:
clock.tick(15)
for event in pygame.event.get():
if event.type == QUIT:
exit()
elif event.type == KEYDOWN:
animating = False
elif event.type == KEYUP:
animating = True
elif event.type == MOUSEBUTTONDOWN:
gif.rewind()
screen.fill((128, 128, 128))
screen.blit(gif.getFrame(), (20, 20))
if animating:
gif.next()
pygame.display.update()