using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
public class LoadImage : MonoBehaviour
{
private int _current;
public int Current
{
get => _current;
set
{
if (value >= 0 && value < 4)
{
_current = value;
return;
}
_current = 0;
}
}
private void Start()
{
Load("/");
Image image = GameObject.Find("Image").GetComponent<Image>();
Current = 0;
image.sprite = images[Current];
Button button = GameObject.Find("Button").GetComponent<Button>();
button.onClick.AddListener(() =>
{
Current++;
image.sprite = images[Current];
});
}
// 储存获取到的图片
List<Texture2D> allTex2d = new List<Texture2D>();
public Sprite[] images;
/// <summary>
/// 读取StremingAssets文件夹指定的文件夹目录下的所有图片进行加载
/// </summary>
/// <param name="path"> StremingAssets文件夹下的文件夹名字 </param>
void Load(string path)
{
List<string> filePaths = new List<string>();
string[] dirs = null;
string imgtype = "*.BMP|*.JPG|*.GIF|*.PNG";
string[] ImageType = imgtype.Split('|');
for (int i = 0; i < ImageType.Length; i++)
{
//获取Application.dataPath文件夹下所有的图片路径
dirs = Directory.GetFiles((Application.streamingAssetsPath + "/" + path), 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(187, 287);
tx.LoadImage(GetImageByte(filePaths[i]));
//获取图片名字,并去除.png 后缀
tx.name = filePaths[i].Substring(filePaths[i].LastIndexOf(@"\") + 1,
filePaths[i].LastIndexOf('.') - filePaths[i].LastIndexOf('\\') - 1);
allTex2d.Add(tx);
}
images = new Sprite[allTex2d.Count];
for (int i = 0; i < allTex2d.Count; i++)
{
images[i] = TextureToSprite(allTex2d[i]);
}
}
/// <summary>
/// 根据图片路径返回图片的字节流byte[]
/// </summary>
/// <param name="imagePath">图片路径</param>
/// <returns>返回的字节流</returns>
public 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;
}
/// <summary>
/// 将Texture2d转换为Sprite
/// </summary>
/// <param name="tex">参数是texture2d纹理</param>
/// <returns></returns>
private Sprite TextureToSprite(Texture2D tex)
{
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
return sprite;
}
}