Unity中加载本地图片

Unity运行时动态加载本地图片的方法,直接上代码,里面很详细。

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour {

    public Image image;
    string localPath = @"D:\Sprites";       //图片存放的文件夹名
    FileInfo[] files;
    int index = 0;      //图片索引


    void Start () {

        //File.Exists(localPath) : 判断某个目录下是否存在某个文件
        //判断是否存在某个文件夹
        if (Directory.Exists(localPath))
        {
            DirectoryInfo direction = new DirectoryInfo(localPath);
            files = direction.GetFiles("*");        //加载什么类型的文件
            Debug.Log(files.Length);

            //localPath + "/" + files[index].Name   : 用于得到文件的路径

            //StartCoroutine(Load(localPath + "/" + files[index].Name));
            LoadByIo(localPath + "/" + files[index].Name);
        }

	}
	
	void Update () {
		
	}

    /// <summary>
    /// 使用www加载
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    IEnumerator Load(string url)
    {
        double startTime = (double)Time.time;
        //请求WWW
        WWW www = new WWW(url);

        yield return www;
        if (www != null && string.IsNullOrEmpty(www.error))
        {
            //获取Texture
            Texture2D texture = www.texture;

            //创建Sprite
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
            image.sprite = sprite;

            startTime = (double)Time.time - startTime;
            Debug.Log("www加载用时 : " + startTime);

        }
    }


    /// <summary>
    /// 以IO方式进行加载
    /// </summary>
    private void LoadByIo(string url)
    {
        double startTime = (double)Time.time;
        //创建文件读取流
        FileStream fileStream = new FileStream(url, FileMode.Open, FileAccess.Read);
        //创建文件长度缓冲区
        byte[] bytes = new byte[fileStream.Length];
        //读取文件
        fileStream.Read(bytes, 0, (int)fileStream.Length);

        //释放文件读取流
        fileStream.Close();
        //释放本机屏幕资源
        fileStream.Dispose();
        fileStream = null;

        //创建Texture
        int width = 300;
        int height = 372;
        Texture2D texture = new Texture2D(width, height);
        texture.LoadImage(bytes);

        //创建Sprite
        Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
        image.sprite = sprite;

        startTime = (double)Time.time - startTime;
        Debug.Log("IO加载" + startTime);

    }

}

参考自:https://www.jianshu.com/p/78372e4f1143

  • 8
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值