unity 通过resouce加载图片_Unity两中方式加载图片

本文介绍如何在Unity中使用IO流和WWW类加载本地图片资源。通过示例代码展示了两种方法的实现过程,并对加载速度进行了简单比较。
摘要由CSDN通过智能技术生成

usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingUnityEngine.UI;usingSystem.IO;public classreadPictures : MonoBehaviour

{privateImage image;private string loadpath = "D:/SOmeOther/NGUI/Assets/StreamingAssets/test.jpg"; //IO方式加载的路径

private string picpathWWW = "test.jpg"; //WWW的加载方式路径//Use this for initialization

private voidStart()

{

image= GetComponent();//IO方法加载速度快//LoadByIO();//WWW 加载速度慢

LoadByWWW();

}private voidLoadByIO()

{double startTime = (double) Time.time;//创建文件流

FileStream fileStream = newFileStream(loadpath, FileMode.Open, FileAccess.Read);

fileStream.Seek(0, SeekOrigin.Begin);//创建文件长度的缓冲区

byte[] bytes = new byte[fileStream.Length];//读取文件

fileStream.Read(bytes, 0, (int) fileStream.Length);//释放文件读取liu

fileStream.Close();

fileStream.Dispose();

fileStream= null;//创建Texture

int width = 300;int height = 372;

Texture2D texture2D= newTexture2D(width, height);

texture2D.LoadImage(bytes);

Sprite sprite= Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height),new Vector2(0.5f, 0.5f));

image.sprite=sprite;double time = (double) Time.time -startTime;

Debug.Log("IO加载用时:" +time);

}private voidLoadByWWW()

{

StartCoroutine(Load());

}private string url = "file://D:/SOmeOther/NGUI/Assets/StreamingAssets/";//private string url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1502532130856&di=7135149ed906483861efdfc9770def3b&imgtype=0&src=http%3A%2F%2Fwww.newasp.net%2Fattachment%2Fsoft%2F2017%2F0811%2F144057_83971519.png"; 这里当然可以换做网络图片的URL 就加载网络图片了

privateIEnumerator Load()

{double startTime = (double) Time.time;

WWW www= new WWW(url + picpathWWW);//只能放URL//WWW www = new WWW(url);//只能放URL 这里可以换做网络的URL

yield returnwww;if (www!=null && string.IsNullOrEmpty(www.error))

{

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;double time = (double)Time.time -startTime;

Debug.Log("WWW加载用时:" +time);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值