第一部分:录制
快速生成Gif 动图其实方式有多种,小编这边直接介绍常用的方式。
方式一:
01我们知道Unity3D 自带录屏Unity Recorder 插件,里面包括生成gif图的功能。Window->Package Manager 直接搜索Unity Recorder关键字。
02然后再选择Window -> General -> Recorder 面板,选择Gif 动画格式即可实现。
方式二:
利用第三方的插件分享,小编特别推荐NatCorder插件。
Pro GIF Recorder Toolkit:
https://assetstore.unity.com/packages/tools/integration/pro-gif-recorder-toolkit-98258
Very Simple GIF:
https://assetstore.unity.com/packages/tools/integration/very-simple-gif-71990
NatCorder - Video Recording API:
下面是NatCorder的实操:
01项目导入插件后,直接设置场景与对象。挂上Giffy组件。
02直接运行项目,实时生成Gif动图。
Gif 示例图:
第二部分:播放
Unity目前对图形图像的支持还不是很完善,支持的图形文件格式有 PSD, TIFF, JPG, TGA, PNG, GIF, BMP, IFF, PICT等,但是针对Gif动画,特别有第三方的插件可以支持。
Gif Play Plugin:
https://assetstore.unity.com/packages/2d/environments/gif-play-plugin-116943
Power GIF Runtime Libary + GIPHY API:
https://assetstore.unity.com/packages/tools/animation/power-gif-runtime-libary-giphy-api-120039
01另外,小编这边直接实操一个简单使用的项目。适用于Window 平台,首先复制”"" file in the "C:\Program Files (x86)\Unity\Editor\Data\Mono\lib\mono\()"文件到"Assets" 文件夹下面;
02然后新建Streaming Assets文件夹,并把命好名称Gif图资源放进去;
03PlayGifAction.cs 关键代码:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using UnityEngine;
///
/// Gif 播放类
///
public class PlayGifAction : 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 = MyGifSet(image);
}
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 ( != 0)
{
for (int i = 0; i < ; i++)
Ims[i].GetComponent().material.mainTexture = tex2DList[index];
}
}
}
private List MyGifSet(System.Drawing.Image image)
{
List tex = new List();
if (image != null)
{
FrameDimension frame = new FrameDimension([0]);
int framCount = (frame);//获取维度帧数
for (int i = 0; i < framCount; ++i)
{
(frame, i);
Bitmap framBitmap = new Bitmap(image.Width, image.Height);
using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(framBitmap))
{
(image, );
}
Texture2D frameTexture2D = new Texture2D(framBitmap.Width, framBitmap.Height, TextureFormat.ARGB32, true);
(Bitmap2Byte(framBitmap));
(frameTexture2D);
}
}
return tex;
}
private byte[] Bitmap2Byte(Bitmap bitmap)
{
using (MemoryStream stream = new MemoryStream())
{
// 将bitmap 以png格式保存到流中
(stream, );
// 创建一个字节数组,长度为流的长度
byte[] data = new byte[];
// 重置指针
(0, );
// 从流读取字节块存入data中
(data, 0, ());
return data;
}
}
}
右滑查看完整代码
04直接运行项目,即可预览Gif图播放显示。