using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.UI;
using System.Reflection;
public class Open : MonoBehaviour
{
private List<Texture2D> images = new List<Texture2D>();
private List<Sprite> spr = new List<Sprite>();
public Image Img1;
private int _index = 0;
void Awake()
{
_index = 0;
}
void Start()
{
load();
Img1.sprite = spr[_index];
}
/// <summary>
/// 加载文件夹内图片
/// </summary>
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++)
{
//获取Application.dataPath文件夹下所有的图片路径
string[] dirs = Directory.GetFiles((Application.streamingAssetsPath + "/Image/"+), ImageType[i]);
for (int j = 0; j < dirs.Length; j++)
{
filePaths.Add(dirs[j]);
Debug.Log(dirs[j]);
}
}
for (int i = 0; i < filePaths.Count; i++)
{
Texture2D tx = new Texture2D(100, 100);
tx.LoadImage(getImageByte(filePaths[i]));
images.Add(tx);
Sprite sprite = Sprite.Create(images[i], new Rect(0, 0, images[i].width, images[i].height), Vector2.zero);
spr.Add(sprite);
}
}
/// <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;
}
}
unity 动态加载图片
最新推荐文章于 2024-07-20 20:43:54 发布