Unity中Gif动图在UGUI上播放
效果图
需要System.Drawing
将System.Drawing.dll 导入工程
下载地址:https://download.csdn.net/download/weixin_40755949/11012009
C#脚本
using System.Collections.Generic;
using UnityEngine;
using System.Drawing;
using System.Drawing.Imaging;
using UnityEngine.UI;
public class DongTu : MonoBehaviour
{
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 + "/BiaoQing.gif"));
}
// Use this for initialization
void Start()
{
}
void Update()
{
sprite1 = Sprite.Create(zhen[dex], new Rect(171, 81,450, 320), 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;
}
}
最后
将脚本挂到需要展示gif动图的UI下就行了,注意放动图文件的路径