untiy 外部加载图片

在unity里面创建StreamingAssets文件夹,

参数是路径,下面是图片的尺寸

方式一

    private Sprite LoadImage(string path)
    {
        Texture2D texture = new Texture2D(701, 395);
        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            fs.Seek(0, SeekOrigin.Begin);
            byte[] bytes = new byte[fs.Length];
            fs.Read(bytes, 0, (int)fs.Length);
            texture.LoadImage(bytes);
        }
        return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
    }

还有一种方式

方式二

获取文件夹下所有图片

 
    // 储存获取到的图片  
    List<Texture2D> allTex2d = new List<Texture2D>();

 /// <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(100, 100);
            tx.LoadImage(Tools.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);
        }
    }




/// <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;
    }

欢迎加入游戏开发交流群C+\C# 636926481

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值