当前位置:   article > 正文

unity 动态加载图片_unity动态加载图片

unity动态加载图片
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;
    }




}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/103491
推荐阅读
相关标签
  

闽ICP备14008679号