Unity3D实现播放gif图功能
程序员文章站
2023-12-11 08:16:46
unity是不识别gif格式图的,需要我们使用c#将gif里多帧图转化为texture2d格式。需要使用system.drawing.dll.此dll在unity安装目录下...
unity是不识别gif格式图的,需要我们使用c#将gif里多帧图转化为texture2d格式。需要使用system.drawing.dll.此dll在unity安装目录下就可以找到。由于unity没有gif格式的文件,所以我们无法在面板指定,需要动态加载。所以将gif图放在streamingassets文件夹下。以下为源代码:
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<texture2d> tex2dlist = new list<texture2d>(); 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<renderer>().material.maintexture = tex2dlist[index]; } } } private list<texture2d> mygif(system.drawing.image image) { list<texture2d> tex = new list<texture2d>(); 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; } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。