Unity简单操作:Unity 里使用Gif图片

87 篇文章 1 订阅
22 篇文章 1 订阅

参考http://wiki.unity3d.com/index.php/AnimatedGifDrawer。

原理是:将gif图拆分成多个单个图片,用Texture2D存放,然后逐个替换Texture2D达到动态效果。

/** 
 *FileName:     gifTest 
 *Author:       #AUTHOR# 
 *Description:    
*/
using System.Drawing;
using System.Drawing.Imaging;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
 
public class GifPlay : MonoBehaviour
{
    public float speed = 1;
 
    private string loadingGifPath;
    private Vector2 drawPosition;
    private UnityEngine.UI.RawImage raw;
    private List<Texture2D> gifFrames = new List<Texture2D>();
 
    void Awake()
    {
        raw = GetComponent<UnityEngine.UI.RawImage>();
 
        loadingGifPath = Application.streamingAssetsPath + "/gif.gif";
        drawPosition = transform.position;
        var gifImage = Image.FromFile(loadingGifPath);
        var dimension = new FrameDimension(gifImage.FrameDimensionsList[0]);
        int frameCount = gifImage.GetFrameCount(dimension);
        for (int i = 0; i < frameCount; i++)
        {
            gifImage.SelectActiveFrame(dimension, i);
            var frame = new Bitmap(gifImage.Width, gifImage.Height);
            System.Drawing.Graphics.FromImage(frame).DrawImage(gifImage, Point.Empty);
            var 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(frame.Width - 1 - x, y, new Color32(sourceColor.R, sourceColor.G, sourceColor.B, sourceColor.A)); // for some reason, x is flipped
                }
            frameTexture.Apply();
            gifFrames.Add(frameTexture);
        }
    }
 
    public IEnumerator PlayGif() {
        for (int i = 0; i < gifFrames.Count; i++)
        {
            raw.texture = gifFrames[i];
            yield return 0;
        }
    }
 
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.P))
        {
            //播放一次
            StartCoroutine(PlayGif());
        }
        //循环播放
        gifFrames[(int)(Time.frameCount * speed) % gifFrames.Count]);
    }
 
    //void OnGUI()
    //{
    //    //GUI.DrawTexture(new Rect(drawPosition.x, drawPosition.y, gifFrames[0].width, gifFrames[0].height), gifFrames[(int)(Time.frameCount * speed) % gifFrames.Count]);
    //}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AD_喵了个咪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值