unity 文件流读取图片与www读取图片的区别介绍
作者:贪玩的孩纸时代
这篇文章主要介绍了unity 文件流读取图片与www读取图片的对比分析,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
IO流代码:
void LoadByIO() { float time = Time.time; 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); fs.Close(); fs.Dispose(); fs = null; Texture2D t = new Texture2D(1,1); t.LoadImage(bytes); img.texture = t; Debug.Log("IO读取图片用时:" + (Time.time-time)); }
WWW代码:
IEnumerator LoadByWWW() { float time = Time.time; WWW w = new WWW("file://" + path); yield return w; if (string.IsNullOrEmpty(w.error) == false) { Debug.Log("error"); } else { img1.texture = w.texture; } Debug.Log("www读取图片用时:" + (Time.time - time)); }
结果截图:
补充:unity加载文件的方法-用加载图片举例
一、用Resources.Load()方法
1、把图片(转换或者不转换为sprite都可)放在Resources里
Texture2D imgTexture = Resources.Load("background_one") as Texture2D; Sprite sprite = Sprite.Create(imgTexture, new Rect(0, 0, imgTexture.width, imgTexture.height), new Vector2(0.5f, 0.5f)); Image image = GetComponent<Image>(); image.sprite = sprite;
2、把图片转换成sprite,放在Resources
//Resources.Load加载图片默认的是Texture2D类型,加了typeof(Sprite)后,就是加载为sprite类型 //然后又转换为object,所以要再用as Sprite转换为Sprite, //如果不加typeof(Sprite),它就是Texture2D转换为object,就不成强制转换为Sprite Image image = GetComponent<Image>(); image.sprite = Resources.Load("background_one", typeof(Sprite)) as Sprite;
二、创建对应文件的public变量,然后再unity里把图片拖给变量赋值
public Sprite play; public Sprite pause; Image image = GetComponent<Image>(); image.sprite = play; image.sprite = pause;
三、用WWW方式,既可以加载网络资源,也可以加载本地资源
//用www方式读取 string path = @"E:\UnityProject\ARVR\Workspace\Test2\Assets\texture\background_one.png"; WWW www = new WWW(path); Texture2D texture = www.texture; Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f)); Image image = GetComponent<Image>(); image.sprite = sprite;
注意:用www加载,最好使用协程,等待图片加载完毕
四、用传统IO流
//创建文件读取流 string path = @"E:\UnityProject\ARVR\Workspace\Test2\Assets\texture\background_one.png"; FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read); fileStream.Seek(0, SeekOrigin.Begin); byte[] bye = new byte[fileStream.Length]; fileStream.Read(bye, 0, bye.Length); fileStream.Close(); //创建texture Texture2D texture2D = new Texture2D(240, 144); texture2D.LoadImage(bye); //创建sprite Sprite sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), new Vector2(0.5f, 0.5f)); Image image = GetComponent<Image>(); image.sprite = sprite;
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。