unity开宝箱动画_Unity3D实现播放gif图功能

该博客介绍了如何在Unity3D中实现播放GIF动图的功能。通过创建一个名为PlayGif的脚本,加载并解析GIF文件,然后在每一帧更新中切换相应的纹理,从而实现动态效果。代码中详细展示了如何从GIF文件中获取每一帧,并将其转换为Unity的Texture2D对象,用于UI Image或Material显示。
摘要由CSDN通过智能技术生成

using System;

using System.Collections;

using System.Collections.Generic;

using System.Drawing;

using System.Drawing.Imaging;

using System.IO;

using UnityEngine;

public class PlayGif : MonoBehaviour {

public UnityEngine.UI.Image Im;

public string gifName = "";

public GameObject[] Ims;

[SerializeField]

private float fps = 5f;

private List tex2DList = new List();

private float time;

Bitmap mybitmp;

void Start()

{

System.Drawing.Image image = System.Drawing.Image.FromFile(Application.streamingAssetsPath + "/"+gifName+".gif");

tex2DList = MyGif(image);

}

// Update is called once per frame

void Update()

{

if (tex2DList.Count > 0)

{

time += Time.deltaTime;

int index = (int)(time * fps) % tex2DList.Count;

if (Im != null)

{

Im.sprite = Sprite.Create(tex2DList[index], new Rect(0, 0, tex2DList[index].width, tex2DList[index].height), new Vector2(0.5f, 0.5f));

}

if (Ims.Length != 0)

{

for (int i = 0; i < Ims.Length; i++)

Ims[i].GetComponent().material.mainTexture = tex2DList[index];

}

}

}

private List MyGif(System.Drawing.Image image)

{

List tex = new List();

if (image != null)

{

//Debug.Log("图片张数:" + image.FrameDimensionsList.Length);

FrameDimension frame = new FrameDimension(image.FrameDimensionsList[0]);

int framCount = image.GetFrameCount(frame);//获取维度帧数

for (int i = 0; i < framCount; ++i)

{

image.SelectActiveFrame(frame, i);

Bitmap framBitmap = new Bitmap(image.Width, image.Height);

using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(framBitmap))

{

graphic.DrawImage(image, Point.Empty);

}

Texture2D frameTexture2D = new Texture2D(framBitmap.Width, framBitmap.Height, TextureFormat.ARGB32, true);

frameTexture2D.LoadImage(Bitmap2Byte(framBitmap));

tex.Add(frameTexture2D);

}

}

return tex;

}

private byte[] Bitmap2Byte(Bitmap bitmap)

{

using (MemoryStream stream = new MemoryStream())

{

// 将bitmap 以png格式保存到流中

bitmap.Save(stream, ImageFormat.Png);

// 创建一个字节数组,长度为流的长度

byte[] data = new byte[stream.Length];

// 重置指针

stream.Seek(0, SeekOrigin.Begin);

// 从流读取字节块存入data中

stream.Read(data, 0, Convert.ToInt32(stream.Length));

return data;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值