1. 程式人生 > 其它 >unity 播放GIF圖片

unity 播放GIF圖片

using System.Collections.Generic;
using UnityEngine;
using System.Drawing;
using System.Drawing.Imaging;
using UnityEngine.UI;

public class DongTu : MonoBehaviour
{
    public string GifName;
    UnityEngine.UI.Image image;
    public float Mytime = 0.05f;
    List<Texture2D> zhen;
    Sprite sprite1;
    
int dex = 0; float time; public int x, y; private void Awake() { image = GetComponent<UnityEngine.UI.Image>(); string path = ""; if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.OSXEditor) { path
= string.Format("{0}/StreamingAssets/", Application.dataPath); } else if (Application.platform == RuntimePlatform.Android) { path = string.Format("{0}!/assets/", Application.dataPath); } else if (Application.platform == RuntimePlatform.IPhonePlayer) { path
= string.Format("{0}/Raw/", Application.dataPath); } zhen = GifToTextureByCS(System.Drawing.Image.FromFile(path + "/"+ GifName + ".gif")); x = zhen[0].width; y = zhen[0].height; } // Use this for initialization void Start() { } void Update() { sprite1 = Sprite.Create(zhen[dex], new Rect( 0, 0, x,y), Vector2.zero); image.sprite = sprite1; time += Time.deltaTime; if (time > Mytime) { dex++; if (dex == zhen.Count) { dex = 0; } time = 0; } } /// <summary> /// gif轉換圖片 /// </summary> /// <param name="image"></param> /// <returns></returns> List<Texture2D> GifToTextureByCS(System.Drawing.Image image) { List<Texture2D> texture2D = null; if (null != image) { texture2D = new List<Texture2D>(); //Debug.LogError(image.FrameDimensionsList.Length); //image.FrameDimensionsList.Length = 1; //根據指定的唯一標識建立一個提供獲取圖形框架維度資訊的例項; FrameDimension frameDimension = new FrameDimension(image.FrameDimensionsList[0]); //獲取指定維度的幀數; int framCount = image.GetFrameCount(frameDimension); for (int i = 0; i < framCount; i++) { //選擇由維度和索引指定的幀; image.SelectActiveFrame(frameDimension, i); var framBitmap = new Bitmap(image.Width, image.Height); //從指定的Image 建立新的Graphics,並在指定的位置使用原始物理大小繪製指定的 Image; //將當前啟用幀的圖形繪製到framBitmap上; System.Drawing.Graphics.FromImage(framBitmap).DrawImage(image, Point.Empty); var frameTexture2D = new Texture2D(framBitmap.Width, framBitmap.Height); for (int x = 0; x < framBitmap.Width; x++) { for (int y = 0; y < framBitmap.Height; y++) { //獲取當前幀圖片畫素的顏色資訊; System.Drawing.Color sourceColor = framBitmap.GetPixel(x, y); //設定Texture2D上對應畫素的顏色資訊; frameTexture2D.SetPixel(x, framBitmap.Height - 1 - y, new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A)); } } frameTexture2D.Apply(); texture2D.Add(frameTexture2D); } } return texture2D; } }

需要引用System.Drawing.dll