pygame风火轮少儿编程正弦字画生成gif

这是用pygame进行图像处理的例子。通过合成图层,pygame可以进行丰富的像素级别的图像处理功能。

"""pygame图像处理之生成风火轮少儿编程正弦gif图.
这个程序生成字图层合成到screen后输出为png文件,最后把所有的png文件又合成一个gif动态文件。
学习了本程序的原理后,就能制作好多gif动画了,比如让字跳动起来,做下雨效果动画gif。"""

__author__ = "李兴球"
__date__ = "2019/3/18"

import pygame,time
from pygame import *
import math,os       # 由于pygame有math,所以要在最后导入math模块
import imageio

def makegif(path,filename):
   """把png文件合成gif文件"""
   images = []
   amount = len(os.listdir(path))   
   for i in range(1,amount+1):
       file = path + os.sep + str(i) + ".png"
       images.append(file)  
   frames = [imageio.imread(image) for image in images]
   imageio.mimsave(filename, frames, 'GIF', duration=0.5) 

path = "C:/" + os.sep + "save"
if not os.path.exists(path):os.mkdir(path)
string = "风火轮少儿编程"
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 360
CENTER_X = SCREEN_WIDTH//2
CENTER_Y = SCREEN_HEIGHT//2
size = (SCREEN_WIDTH,SCREEN_HEIGHT)

pygame.init()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("pygame风火轮少儿编程正弦字画生成gif示例_作者:李兴球")
screen.fill((255,255,255))
msyhfont = pygame.font.Font('msyh.ttf',24)  # 新建微软雅黑字体

i = 0
counter = 0
for angle in range(-180,181,26):    
    x = CENTER_X + angle
    y = CENTER_Y + 70 * math.sin(math.radians(angle))
    y = int(y)
    char = string[i]    # 取一个汉字
    i = i + 1
    i = i % len(string)
    counter = counter + 1 # 下面这句是合成图像层
    txt_image = msyhfont.render(char,True,(255,0,255))
    txt_rect = txt_image.get_rect()
    txt_rect.center = x,y
    screen.blit(txt_image,txt_rect)
    filename = path + os.sep + str(counter) + ".png"
     
    pygame.image.save(screen,filename)   # 保存到png文件
    pygame.display.update()
pygame.quit()
makegif(path,string + ".gif")