Unity制作GIF动画播放组件

Unity制作GIF动画播放组件(无需System.Drawing)

效果图

效果图

封装后的组件效果

GIF播放组件

使用方法

  • Is Play On Start:自动播放
  • Path: GIF路径
  • Is Use Fixed Frame Rate:是否使用固定的帧率
  • Frame Rate:固定的帧率
  • Loop:是否循环播放

使用固定帧率如果被勾选,则忽略gif文件每帧的延时设定,并采用FrameRate给定的值。如果不勾选,则读取gif文件设定的值。

组件的方法:

  • Play(bool bRewind=false):播放,bRewind表示是否重头开始播。
  • Pause():暂停
  • Stop():停止
  • Free():停止并释放资源

核心代码

private void LoadGif()
{
    
    
	images = null;
	if (!System.IO.File.Exists(Path))
		return;
	if (!Path.EndsWith(".gif", System.StringComparison.OrdinalIgnoreCase))
		return;

	byte[] fileContent = System.IO.File.ReadAllBytes(Path);
	List<GifImages> list = new List<GifImages>();
	
	using( Decoder gifImage = new Decoder( fileContent ))
	{
    
    
		var image = gifImage.NextImage();
		while( image != null )
		{
    
    
			Texture2D tex = image.CreateTexture();
			Sprite sp = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
			sp.name = $"GIF_{
      
      list.Count:000}";
			float dy = image.Delay / 1000f;

			list.Add(new GifImages()
			{
    
    
				sprite = sp,
				delay = dy
			});

			image = gifImage.NextImage();
		}
	}
	
	if (list.Count > 0)
		images = list.ToArray();
}

源码下载

点击此处下载源码

猜你喜欢

转载自blog.csdn.net/sdhexu/article/details/124150848
今日推荐