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