hello ,哈哈,第一次寫博客略微有點小激動。在博客裏寫下自己平常的積累還是不錯的,決定以後有的新的問題及解決方案都寫出來共享一下。
前幾天有朋友問我unity裏怎麼從某個文件夾下把所有的圖片獲取到,並且要能隨時顯示出來,於是我就寫了一個如下簡單的例子,如有不妥之處望多指教:
using UnityEngine;
using System.Collections.Generic;
using System.IO;
public class LoadImage : MonoBehaviour
{
// 儲存獲取到的圖片
List<Texture2D> allTex2d = new List<Texture2D> ();
// Use this for initialization
void Start ()
{
load ();
}
void OnGUI ()
{
if (allTex2d.Count != 0) {
// 把加載的圖片顯示出來
for (int i = 0; i < allTex2d.Count; i++) {
GUILayout.Button (allTex2d [i]);
}
}
}
void load ()
{
List<string> filePaths = new List<string> ();
string imgtype = "*.BMP|*.JPG|*.GIF|*.PNG";
string[] ImageType = imgtype.Split ('|');
for (int i = 0; i < ImageType.Length; i++) {
//獲取d盤中a文件夾下所有的圖片路徑
string[] dirs = Directory.GetFiles (@"d:\\a", ImageType [i]);
for (int j = 0; j < dirs.Length; j++) {
filePaths.Add (dirs [j]);
}
}
for (int i = 0; i < filePaths.Count; i++) {
Texture2D tx = new Texture2D (100, 100);
tx.LoadImage (getImageByte (filePaths [i]));
allTex2d.Add (tx);
}
}
/// <summary>
/// 根據圖片路徑返回圖片的字節流byte[]
/// </summary>
/// <param name="imagePath">圖片路徑</param>
/// <returns>返回的字節流</returns>
private static byte[] getImageByte (string imagePath)
{
FileStream files = new FileStream (imagePath, FileMode.Open);
byte[] imgByte = new byte[files.Length];
files.Read (imgByte, 0, imgByte.Length);
files.Close ();
return imgByte;
}
}