将Gif图转换成Unity Texture2D
发表于2018-09-02
最近项目里要从网上拉取玩家的头像,可玩家的头像可以用gif图但unity不支持gif图,这样就会出现拉取失败会显示问号的图,那是Unity内转换Texture2D图失败是给的默认图。于是在网上查找解决方案,果然在http://wiki.unity3d.com/index.php/AnimatedGifDrawer上找到了;将Gif图转换成Unity Texture2D的原理是:将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图转换成Unity Texture2D的方法,希望能对大家有帮助,
来自:https://blog.csdn.net/hyf2713/article/details/52452854