Unity 播放Gif 圖片
阿新 • • 發佈:2020-07-28
1.在Unity 檔案目錄下找到 system.Drawing.dll ,把它放在Assets 目錄下
2. 在PlayerSetting 把.Net2.0 換成 Net4.0
3.
using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using UnityEngine; public class PlayGif : MonoBehaviour { publicbool OnecState = false; public bool loopState = false; public UnityEngine.UI.Image Im; public string gifName = ""; public GameObject[] Ims; [SerializeField] private float fps = 5f; private List<Texture2D> tex2DList = new List<Texture2D>(); private float time; Bitmap mybitmp;void Start() { System.Drawing.Image image = System.Drawing.Image.FromFile(Application.streamingAssetsPath + "/" + gifName + ".gif"); tex2DList = MyGif(image); } // Update is called once per frame void Update() { if (tex2DList.Count > 0&&(OnecState || loopState)) { time+= Time.deltaTime; int index = (int)(time * fps) % tex2DList.Count; if (Im != null) { Im.sprite = Sprite.Create(tex2DList[index], new Rect(0, 0, tex2DList[index].width, tex2DList[index].height), new Vector2(0.5f, 0.5f)); } if (Ims.Length != 0) { for (int i = 0; i < Ims.Length; i++) Ims[i].GetComponent<Renderer>().material.mainTexture = tex2DList[index]; } if (index == tex2DList.Count-1) { OnecState = false; time = 0; } } } private List<Texture2D> MyGif(System.Drawing.Image image) { List<Texture2D> tex = new List<Texture2D>(); if (image != null) { //Debug.Log("圖片張數:" + image.FrameDimensionsList.Length); FrameDimension frame = new FrameDimension(image.FrameDimensionsList[0]); int framCount = image.GetFrameCount(frame);//獲取維度幀數 for (int i = 0; i < framCount; ++i) { image.SelectActiveFrame(frame, i); Bitmap framBitmap = new Bitmap(image.Width, image.Height); using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(framBitmap)) { graphic.DrawImage(image, Point.Empty); } Texture2D frameTexture2D = new Texture2D(framBitmap.Width, framBitmap.Height, TextureFormat.ARGB32, true); frameTexture2D.LoadImage(Bitmap2Byte(framBitmap)); tex.Add(frameTexture2D); } } return tex; } 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; } } }