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); } }
