Unity3d:加载Gif格式图片
unity里不支持Gif格式的图片,网上搜索也没有相关资料,殊不知我们已经太相信度娘了,而没有了自己的分析,我们知道Gif图是由多个静态图做成的,那我们就回归本土,第一步:把gif拆成n个静态图放在集合里
/// <summary> /// 拆分GIF(使用.Net框架的Image对象) /// </summary> /// <returns>The GIF.</returns> /// <param name="path">Path.</param> public static System.Collections.Generic.List<Texture> SeparateGif(string path) { System.Collections.Generic.List<Texture> list=new List<Texture>(); try { // 获取图片对象 System.Drawing.Image imgGif = System.Drawing.Image.FromFile(path); // 先判断图片是否是动画图片(gif) if (System.Drawing.ImageAnimator.CanAnimate(imgGif)) { System.Drawing.Imaging.FrameDimension imgFrmDim = new System.Drawing.Imaging.FrameDimension(imgGif.FrameDimensionsList[0]); // 获取帧数 int nFdCount = imgGif.GetFrameCount(imgFrmDim); for (int i = 0; i < nFdCount; i++) { // 把每一帧保存为jpg图片 imgGif.SelectActiveFrame(imgFrmDim, i); Texture2D t2 = new Texture2D(imgGif.Width, imgGif.Height); t2.LoadImage(ImageToByteArray(imgGif)); list.Add((Texture)t2); } } } catch (Exception ex) { } return list; }
第二步:把集合中的图绘制出来
private System.Collections.Generic.List<Texture> anim; private int nowFram; private int mFrameCount; private float fps = 1.2f; private float time = 0; void OnGUI() { DrawAnimation(anim, new Rect(float.Parse((Screen.width/2-(int)EleWidth/2+czdaGo.transform.localPosition.x).ToString()),float.Parse((Screen.height/2-(int)EleHeight/2-czdaGo.transform.localPosition.y-40).ToString()), (int)EleWidth, (int)EleHeight)); } /// <summary> /// Draws the animation. /// </summary> /// <param name="tex">Tex.</param> /// <param name="rect">Rect.</param> void DrawAnimation(System.Collections.Generic.List<Texture> tex, Rect rect) { try { GUI.DrawTexture(rect, tex[nowFram], ScaleMode.StretchToFill, true, 0); time += Time.deltaTime; if (time >= 1.0 / fps) { nowFram++; time = 0; if (nowFram >= mFrameCount) { nowFram = 0; } } } catch (System.Exception ex) { Debug.Log("CZDAElementGifInfo_DrawAnimation():"+ex.Message); } }