最近项目里要从网上拉取玩家的头像,可玩家的头像可以用gif图但unity不支持gif图,这样就会出现拉取失败会显示问号的图,那是Unity内转换Texture2D图失败是给的默认图。于是在网上查找解决方案,果然在http://wiki.unity3d.com/index.php/AnimatedGifDrawer上找到了;其原理是:将gif图拆分成多个单个图片,用Texture2D存放,然后逐个替换Texture2D达到动态效果。
下面是我根据用上面连接里的代码做的测试:
using UnityEngine;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
/*
这里引用的System.Drawing是在C:\Program Files (x86)\Unity\Editor\Data\Mono\lib\mono\2.0目录下,这个是unity安装的目录;
*/
public class GifToTexture : MonoBehaviour
{
public UITexture GifTexture;
private List<Texture2D> _mTexture2Ds = new List<Texture2D>();
private float _mTime;
private float _mSpeed = 5.0f;
// Use this for initialization
void Start ()
{
Image image = Image.FromFile(@"G:\1405069286948.gif");
_mTexture2Ds = GifToTextureByCS(image);
}
// Update is called once per frame
void Update () {
if (null != GifTexture && _mTexture2Ds.Count > 0)
{
_mTime += Time.deltaTime;
int index = (int)(_mTime*_mSpeed)%_mTexture2Ds.Count;
GifTexture.mainTexture = _mTexture2Ds[index];
}
}
List<Texture2D> GifToTextureByCS(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图我上传上面代码只要调好时间效果就和这个差不多了
好像可以获取到每帧图的时间间隔,这个下次去网上查查,再记录下吧。今天就到这,感谢http://wiki.unity3d.com/index.php/AnimatedGifDrawer作者代码的分享。