赞
踩
本文参考这篇文章。
加载整个StreamingAssets文件夹中某个文件下的所有图片,我加载的是StreamingAssets文件夹中Pictures下的所有图片。
加载的图片存在allTex2d中,若要将其转换成sprite格式并显示,可以用images[i].sprite = TextureToSprite(allTex2d[i]);(其中images是需要贴上sprite的Image)
- // 储存获取到的图片
- List<Texture2D> allTex2d = new List<Texture2D>();
- //public Image[] 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]);
- }
- }
-
- Debug.Log("图片数量:" + dirs.Length);
-
- 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);
- Debug.Log("Texture2D Name:" + tx.name + ".png");
- }
- // for(int i = 0; i < allTex2d.Count; i++)
- //{
- // images[i].sprite = 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;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。