需要导入System.Drawing这个dll文件放进unity,但是我放进去以后报错相同的命名空间却有二个版本是因为这个依赖的版本不是统一的
/// <summary>
/// Unity播放GIf动画
/// </summary>
public class GIf : MonoBehaviour
{
public System.Drawing.Image gifImage; //gif图片
public UnityEngine.UI.Image image; //显示gif的UI
public string windowPath = "game_start.gif"; //windons的gif的路径
public string EditorPath = "game_start.gif"; //Editor的路径
private float fps = 15;
private List<Texture2D> text2DList; //gif拆成的图片
private float time;
void Start()
{
//打包时路径 需要将gif图片放在StreamingAssets里
gifImage = System.Drawing.Image.FromFile(Application.streamingAssetsPath + "/" + windowPath);
编译器下或者Iphone平台
//gifImage = System.Drawing.Image.FromFile(Application.dataPath + "/" + EditorPath);
text2DList = GifToTexture2D(gifImage);
}
List<Texture2D> GifToTexture2D(System.Drawing.Image gifImage)
{
List<Texture2D> target = null;
if (gifImage != null)
{
target = new List<Texture2D>();
//Debug.Log("dimenson:" + gifImage.FrameDimensionsList.Length);
FrameDimension frameDimension = new FrameDimension(gifImage.FrameDimensionsList[0]);
int frameCount = gifImage.GetFrameCount(frameDimension);
for (int i = 0; i < frameCount; i++)
{
gifImage.SelectActiveFrame(frameDimension, i);
//创建Bitmap的实例
Bitmap frameBitmap = new Bitmap(gifImage.Width, gifImage.Height);
//Save
//frameBitmap.Save(Application.dataPath + "/" + i + ".png", ImageFormat.Png);
//将GifImage通过Graphics画到Bitmap上
using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(frameBitmap))
{
graphics.DrawImage(gifImage, Point.Empty);
}
//创建Texture2D的实例
Texture2D frameTexture2D = new Texture2D(frameBitmap.Width, frameBitmap.Height, TextureFormat.ARGB32, true);
frameTexture2D.LoadImage(Bitmap2Byte(frameBitmap));
target.Add(frameTexture2D);
}
}
return target;
}
private byte[] Bitmap2Byte(Bitmap bitmap)
{
using (MemoryStream stream = new MemoryStream())
{
//将bitmap可以以png格式保存到流中
bitmap.Save(stream, ImageFormat.Png);
//创建一个字节数组,长度为流的长度
byte[] data = new byte[stream.Length];
//重置指针
stream.Seek(0, SeekOrigin.Begin);
//从流读取字节数组块存入data中
stream.Read(data, 0, Convert.ToInt32(stream.Length));
return data;
}
}
void Update()
{
if (text2DList.Count > 0)
{
time += Time.deltaTime;
int index = (int)(time * fps) % text2DList.Count;
if (image != null)
{
Sprite sprite = Sprite.Create(text2DList[index],
new Rect(0, 0, text2DList[index].width, text2DList[index].height),
new Vector2(0.5f, 0.5f));
image.overrideSprite = sprite;
}
}
}
}