using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour {
public Image image;
string localPath = @"D:\Sprites"; //圖片存放的文件夾名
FileInfo[] files;
int index = 0; //圖片索引
void Start () {
//File.Exists(localPath) : 判斷某個目錄下是否存在某個文件
//判斷是否存在某個文件夾
if (Directory.Exists(localPath))
{
DirectoryInfo direction = new DirectoryInfo(localPath);
files = direction.GetFiles("*"); //加載什么類型的文件
Debug.Log(files.Length);
//localPath + "/" + files[index].Name : 用於得到文件的路徑
//StartCoroutine(Load(localPath + "/" + files[index].Name));
LoadByIo(localPath + "/" + files[index].Name);
}
}
void Update () {
}
/// <summary>
/// 使用www加載
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
IEnumerator Load(string url)
{
double startTime = (double)Time.time;
//請求WWW
WWW www = new WWW(url);
yield return www;
if (www != null && string.IsNullOrEmpty(www.error))
{
//獲取Texture
Texture2D texture = www.texture;
//創建Sprite
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
image.sprite = sprite;
startTime = (double)Time.time - startTime;
Debug.Log("www加載用時 : " + startTime);
}
}
/// <summary>
/// 以IO方式進行加載
/// </summary>
private void LoadByIo(string url)
{
double startTime = (double)Time.time;
//創建文件讀取流
FileStream fileStream = new FileStream(url, FileMode.Open, FileAccess.Read);
//創建文件長度緩沖區
byte[] bytes = new byte[fileStream.Length];
//讀取文件
fileStream.Read(bytes, 0, (int)fileStream.Length);
//釋放文件讀取流
fileStream.Close();
//釋放本機屏幕資源
fileStream.Dispose();
fileStream = null;
//創建Texture
int width = 300;
int height = 372;
Texture2D texture = new Texture2D(width, height);
texture.LoadImage(bytes);
//創建Sprite
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
image.sprite = sprite;
startTime = (double)Time.time - startTime;
Debug.Log("IO加載" + startTime);
}
}
https://blog.csdn.net/qq_38721111/article/details/90711710