首先复制"System.Drawing.dll" file in the "C:\Program Files (x86)\Unity\Editor\Data\Mono\lib\mono\2.0"文件到"Assets" 文件夹下面
播放的原理其实就是把GIF图片,转换为一张一张的图片,再去播放出来的。
不过在使用的过程中,加载图片有点慢,如果是要打开场景立即使用,可能没有达到你想要的效果。
好了晒出来源码 :
using System.Drawing;
using System.Drawing.Imaging;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AnimatedGifDrawer : MonoBehaviour
{
public float speed = 5;
private string loadingGifPath;
private Vector2 drawPosition;
private UnityEngine.UI.RawImage raw;
private List<Texture2D> gifFrames = new List<Texture2D>();
void Awake()
{
raw = GetComponent<UnityEngine.UI.RawImage>();
loadingGifPath = Application.streamingAssetsPath + "/test3.gif";
drawPosition = transform.position;
var gifImage = System.Drawing.Image.FromFile(loadingGifPath);
var dimension = new FrameDimension(gifImage.FrameDimensionsList[0]);
int frameCount = gifImage.GetFrameCount(dimension);
for (int i = 0; i < frameCount; i++)
{
gifImage.SelectActiveFrame(dimension, i);
var frame = new Bitmap(gifImage.Width, gifImage.Height);
System.Drawing.Graphics.FromImage(frame).DrawImage(gifImage, Point.Empty);
var frameTexture = new Texture2D(frame.Width, frame.Height);
for (int x = 0; x < frame.Width; x ++)
{
for (int y = 0; y < frame.Height; y ++)
{
System.Drawing.Color sourceColor = frame.GetPixel(x, y);
frameTexture.SetPixel(frame.Width - 1 - x, y, new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A)); // for some reason, x is flipped
//frameTexture.SetPixel(frame.Width - 1 - x+1, y+1, new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A)); // for some reason, x is flipped
}
}
frameTexture.Apply();
gifFrames.Add(frameTexture);
}
}
public IEnumerator PlayGif()
{
for (int i = 0; i < gifFrames.Count; i++)
{
raw.texture = gifFrames[i];
yield return 0;
}
}
private void Update()
{
//if (Input.GetKeyDown(KeyCode.P))
//{
// //播放一次
// StartCoroutine(PlayGif());
//}
//循环播放
raw.texture = gifFrames[(int)((Time.frameCount * speed) % gifFrames.Count)];
}
}
替换里面的文件,就可以播放出来了。如果有什么好的方法,欢迎提出来或者留言。