WWW和IO方式加载图片到UGUI的Image上显示出来对比
2017-05-17 本文已影响0人
HMY轩园
WWW和IO方式加载图片到UGUI的Image上显示出来对比,后者所用时间较短,速度快,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
public class wwwLoadImage : MonoBehaviour {
public Image image;
public Image image2;
// Use this for initialization
void Start () {
Debug.Log(Application.dataPath);
StartCoroutine(GetImage());
GetImageByIO();
}
// Update is called once per frame
void Update () {
}
IEnumerator GetImage() {
double startTime = (double)Time.time;
WWW www = new WWW(@"file://"+ Application.dataPath+"/logo.png");
yield return www;
if (www.error!=null)
{
yield return null;
}
Texture2D texture = www.texture;
GetImage(texture, image);
startTime = (double)Time.time - startTime;
Debug.Log("WWW加载用时:" + startTime);
}
/// <summary>
/// 以IO方式进行加载
/// </summary>
void GetImageByIO() {
double startTime=(double)Time.time;
//创建文件读取流 路径 创建模式 读取权限
FileStream fileSteam = new FileStream(Application.dataPath + "/logo.png", FileMode.Open, FileAccess.Read);
fileSteam.Seek(0, SeekOrigin.Begin);
//创建文件长度缓冲区
byte[] bytes = new byte[fileSteam.Length];
//读取文件
fileSteam.Read(bytes, 0, (int)fileSteam.Length);
//释放文件读取流
fileSteam.Close();
fileSteam.Dispose();
fileSteam = null;
Texture2D tex = new Texture2D(200, 100);
tex.LoadImage(bytes);
GetImage(tex, image2);
startTime = (double)Time.time - startTime;
Debug.Log("IO加载用时:" + startTime);
}
private void GetImage(Texture2D tex, Image image) {
//创建Sprite
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
image.sprite = sprite;
image.SetNativeSize();
}
}