简体   繁体   中英

How to make gif at pygame?

I have 6 photos that I wanna make gif from them and show it on Pygame. I get that I can't preview it so simply, so what I can do to show the animation like a gif?

Python 2.7

You can create a class that switch between your images based on a time interval.

class Animation(pygame.sprite.Sprite):

    def __init__(self, images, time_interval):
        super(Animation, self).__init__()
        self.images = images
        self.image = self.images[0]
        self.time_interval = time_interval
        self.index = 0
        self.timer = 0

    def update(self, seconds):
        self.timer += seconds
        if self.timer >= self.time_interval:
            self.image = self.images[self.index]
            self.index = (self.index + 1) % len(self.images)
            self.timer = 0

I created a small sample program to try it out.

import pygame
import sys

pygame.init()


class Animation(pygame.sprite.Sprite):

    def __init__(self, images, time_interval):
        super(Animation, self).__init__()
        self.images = images
        self.image = self.images[0]
        self.time_interval = time_interval
        self.index = 0
        self.timer = 0

    def update(self, seconds):
        self.timer += seconds
        if self.timer >= self.time_interval:
            self.image = self.images[self.index]
            self.index = (self.index + 1) % len(self.images)
            self.timer = 0


def create_images():
    images = []
    for i in xrange(6):
        image = pygame.Surface((256, 256))
        image.fill((255 - i * 50, 255, i * 50))
        images.append(image)
    return images


def main():
    images = create_images()  # Or use a list of your own images.
    a = Animation(images, 0.25)

    # Main loop.
    while True:
        seconds = clock.tick(FPS) / 1000.0  # 'seconds' is the amount of seconds each loop takes.

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        a.update(seconds)
        screen.fill((0, 0, 0))
        screen.blit(a.image, (250, 100))
        pygame.display.update()


if __name__ == '__main__':
    screen = pygame.display.set_mode((720, 480))
    clock = pygame.time.Clock()
    FPS = 60
    main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM