Unity是不識別Gif格式圖的,需要我們使用c#將gif里多幀圖轉化為Texture2D格式。需要使用System.Drawing.dll.此dll在unity安裝目錄下就可以找到。由于unity沒有gif格式的文件,所以我們無法在面板指定,需要動態加載。所以將gif圖放在StreamingAssets文件夾下。以下為源代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
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; } } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_33994566/article/details/86534969