Unity解析gif动态图操作

工作需求,要播放一张gif图片,又不想转成视频播放,就开始研究怎样解析gif,在网上也看了不少教程,最后根据自己需求写了个脚本。

首先,Unity是不支持gif的(至少我没找到方法),而又要在NGUI中显示gif图片。所以就想到了将gif解析成序列帧再去循环播放。

有人说可以找软件解析,然后导入Unity做动画,最终我没有采用,自己再Unity中以代码解析,然后播放的。

代码如下

(在Awake中解析的,因为要在其他脚本调用,实时解析的话,到时候会花费一会时间):

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

using UnityEngine;

public class AnimatedGifDrawer : MonoBehaviour
{
    public string loadingGifPath;//路径
    public UITexture tex;//图片
    public float speed = 0.1f;//播放速度

    private bool isPlay = false;//是否播放
    private int i = 0;//控制要播放的图片

    private List<Texture2D> gifFrames = new List<Texture2D>();//存储解析出来的图片
    void Awake()
    {
        Image gifImage = Image.FromFile(loadingGifPath);
        FrameDimension dimension = new FrameDimension(gifImage.FrameDimensionsList[0]);
        int frameCount = gifImage.GetFrameCount(dimension);
        for (int i = 0; i < frameCount; i++)
        {
            gifImage.SelectActiveFrame(dimension, i);
            Bitmap frame = new Bitmap(gifImage.Width, gifImage.Height);
            System.Drawing.Graphics.FromImage(frame).DrawImage(gifImage, Point.Empty);
            Texture2D frameTexture = new Texture2D(frame.Width, frame.Height);
            for (int x = 0; x < frame.Width; x++)
                for (int y = 0; y < frame.Height; y++)
                {
                    System.Drawing.Color sourceColor = frame.GetPixel(x, y);
                    frameTexture.SetPixel( x, frame.Height - 1 - y, new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A)); // for some reason, x is flipped
                }
            frameTexture.Apply();
            gifFrames.Add(frameTexture);
        }
    }

    private void Update()
    {
        if (isPlay == true)
        {
            i++;
            tex.mainTexture = gifFrames[(int)(i * speed) % gifFrames.Count];
        }
    }

    /// <summary>
    /// 播放动画
    /// </summary>
    public void StartAni()
    {
        isPlay = true;
    }

    /// <summary>
    /// 停止动画
    /// </summary>
    public void StopAni()
    {
        isPlay = false;
        i = 0;
    }
}

补充:Unity播放GIF插件,不使用第三方库,基于文件协议,纯代码实现,兼容移动端和序列帧

本人通过分析GIF的文件协议,分解GIF的各序列帧,然后封装成Unity可使用的Texture,通过递归播放,实现了在Unity上播放GIF的功能,并发布到了AssetStore上面,欢迎各位朋友交流经验。

核心源码:

分解GIF

//处理每个图块
            for (int index = 0; index < gif.GraphicControlExtensions.Count; index++)
            {
                //命名
                textureDescriptor.name = "Frame" + (index + 1);

                //图像描述器
                ImageDescriptor imageDescriptor = gif.ImageDescriptors[index];

                //像素色号集
                byte[] colorIndexs = imageDescriptor.GetColorIndexs();

                //绘图控制扩展
                GraphicControlExtension control = gif.GraphicControlExtensions[index];

                //像素指针
                int pixelIndex = 0;

                //gif的像素点顺序 左上到右下,unity的像素顺序是 左下到右上,所以y套x, y翻转一下
                for (int y = imageDescriptor.MarginTop; y < imageDescriptor.MarginTop + imageDescriptor.Height; y++)
                {
                    for (int x = imageDescriptor.MarginLeft; x < imageDescriptor.MarginLeft + imageDescriptor.Width; x++)
                    {
                        Color32 colorPixel = imageDescriptor.GetColor(colorIndexs[pixelIndex++], control, gif);
                        if (colorPixel.a == 0 && reserve)
                            continue;
                        textureDescriptor.SetPixel(x, gif.Height - y - 1, colorPixel);
                    }
                }

                //保存
                textureDescriptor.Apply();

                //添加序列帧
                Sprite sprite = Sprite.Create(textureDescriptor, new Rect(0, 0, textureDescriptor.width, textureDescriptor.height), Vector2.zero);
                sprite.name = textureDescriptor.name;
                frames.Add(new UnityFrame(sprite, control.DelaySecond));

                //初始化图像
                textureDescriptor = new Texture2D(gif.Width, gif.Height);
                reserve = false;

                //下一帧图像预处理
                switch (control.DisposalMethod)
                {
                    //1 - Do not dispose. The graphic is to be left in place. //保留此帧
                    case DisposalMethod.Last:
                        textureDescriptor.SetPixels(frames[index].Texture.GetPixels());
                        reserve = true;
                        break;

                    //2 - Restore to background color. The area used by the graphic must be restored to the background color. //还原成背景色
                    case DisposalMethod.Bg:
                        textureDescriptor.SetPixels(textureBg.GetPixels());
                        break;

                    //3 - Restore to previous. The decoder is required to restore the area overwritten by the graphic with what was there prior to rendering the graphic.//还原成上一帧
                    case DisposalMethod.Previous:
                        textureDescriptor.SetPixels(frames[index - 1].Texture.GetPixels());
                        reserve = true;
                        break;
                }
            }

递归播放

       /// <summary>
        /// 递归播放
        /// </summary>
        /// <returns></returns>
        IEnumerator Play()
        {
            if (mStop)
            {
                mFrameIndex = 0;
                yield break;
            }

            //帧序号
            mFrameIndex = mFrameIndex % mFrames.Count;
            //绘图
            if (mRawImage)
                mRawImage.texture = mFrames[mFrameIndex].Texture;
            if (mImage)
                mImage.sprite = mFrames[mFrameIndex].Sprite;
            //帧延时
            yield return new WaitForSeconds(mFrames[mFrameIndex].DelaySecond);
            //序号++
            mFrameIndex++;

            //播放一次
            if (!Loop && mFrameIndex == mFrames.Count)
                yield break;

            //递归播放下一帧
            StartCoroutine(Play());
        }

插件支持GIF播放和序列帧播放。 插件支持透明颜色。

插件通过GIF文件协议将图像转换为Unity支持的图像,所有的实现都是通过C#代码,所以你可以很容易的修改代码,以达到你的需求。

插件支持Image和RawImage两种组件,当然你可以改造一下支持其他组件。

插件支持3种播放模式:

1、通过GIF的文件路径

2、通过拖拽GIF的二进制文件

3、通过拖拽序列帧

例子放在文件夹Assets\Plugin\GifPlayer\Dome\中。

欢迎使用。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。如有错误或未考虑完全的地方,望不吝赐教。

(0)

相关推荐

  • Unity3D启动外部程序并传递参数的实现

    之前开发项目,一直都使用的是外壳程序加子程序的模式,通过外壳程序去启动子程序,外壳程序和子程序之间的通信,是使用配置文件完成的. 我总觉得这样通信很麻烦,因为外壳程序需要对配置文件进行更改和写入,然后子程序又要读取信息.而且整合的时候,会导致有很多配置文件,而且需要对路径做很多处理和限制. 我发现Process.Start()函数中,是可以传递参数的. 也就是说,我们是可以在使用Process.Start()函数启动外部程序时,传递参数的进行通信的. 具体操作如下: public void St

  • unity 如何获取Text组件里text内容的长度

    我就废话不多说了,大家还是直接看代码吧~ /// <summary> /// 计算字符串在指定text控件中的长度 /// </summary> /// <param name="message"></param> /// <returns></returns> int CalculateLengthOfText(string message,Text tex) { int totalLength = 0; Fon

  • Unity使用物理引擎实现多旋翼无人机的模拟飞行

    内容简介 最近在用Unity实现无人机的模拟飞行,但发现站里基本没有完整介绍如何实现该功能的博客,因时间紧迫,就自己简单做了一个仿真(不是完全按照现实物理情景来做,即通过各个螺旋桨旋转产生力带动机体飞行).下面我会简述完全按现实物理情景实现模拟飞行,并详细描述我自己做的模拟飞行(不完全仿真),给各位提供参考. 现实物理情景的实现--简述(以四旋翼无人机为例) 因为我没有实现1:1仿真,所以这里只介绍思路,希望能给到读者一点启发. 构建一个四旋翼无人机模型(可以网上下载.或用Maya等建一个) 将

  • unity avprovideo插件的使用详解

    1.新建一个MediaPlayer组件 2.在canvas下新建一个AVProVideo组件 并将上一步新建的MediaPlayer组件赋值到avprovideo组件上的mediaplayer上 3.将需要播放的视频放在StreamingAssets文件夹下 接下来就是用代码调用了 1._mediaPlayer.OpenVideoFromFile(MediaPlayer.FileLocation.RelativeToStreamingAssetsFolder, 视频路径, 是否自动播放);//加

  • unity 如何获取button文本的内容

    如下就可以获取button中的文本内容 using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; public class ButtonContent : MonoBehaviour{ public Button btn; void Start(){ btn = GameObject.Find("填写button名").getComponent<Button&g

  • Unity3d 如何更改Button的背景色

    我就废话不多说了,大家还是直接看代码吧~ using UnityEngine; using System.Collections; public class ButtonStyle : MonoBehaviour { public Color _color;//在编辑环境下选择背景色,透明度不能为0 public Texture2D tex; void OnGUI(){GUI.Button(new Rect(0,0,100,100),"tex");Color oldColor = GU

  • unity里获取text中文字宽度并截断省略的操作

    前言 在unity的ugui中Text控件,有时我们会有各种各样的需求,比如类似html中css的text-overflow属性,希望一段文字如果不够长就全显示,如果特别长就截断并且后面加上例如-这种后缀. 好吧这样的需求在ugui里貌似没有现成的方法,如果有的话麻烦指点一下~ 实现 大概的思路就是 - 首先要能判断什么时候overflow - 并且支持加上后缀 那么text控件本来是支持overflow然后直接截断的,但是比较暴力,直接砍断,不能加后缀,并不满足我们的需求. 然后如果简单的通过

  • Unity3D 单例模式和静态类的使用详解

    Unity3D的API提供了很多的功能,但是很多流程还是会自己去封装一下去.当然现在网上也有很多的框架可以去下载使用,但是肯定不会比自己写的用起来顺手. 对于是否需要使用框架的问题上,本人是持肯定态度的,把一些常用方法进行封装,做成一个功能性的框架,可以很大程度上提高代码的效率,维护也方便. 对于网络上很多教程上使用的"游戏通用MVC框架",现在看来并不符合MVC这种结构性框架的设计思想:要知道,MVC最初是被设计为Web应用的框架,而游戏中的很多事件并不是通过用户点击UI发生的,Vi

  • unity 如何使用文件流读取streamingassets下的资源

    目的:读取streamingassets下的文件中指定的一段字节 已知:文件中的起始位置,和需要读取的长度 1.android下读取 1.1 不能直接使用C#的FileStream,读取失败 var buffer = new byte[size]; FileStream stream = File.OpenRead(path); stream.Read(buffer , pos, size); 报错: IsolatedStorageException: Could not find a part

  • unity 文件流读取图片与www读取图片的区别介绍

    IO流代码: void LoadByIO() { float time = Time.time; FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); fs.Seek(0, SeekOrigin.Begin); byte[] bytes = new byte[fs.Length]; fs.Read(bytes, 0, (int)fs.Length); fs.Close(); fs.Dispose(); fs =

随机推荐