unity读取Texture文件并转为Sprit

时间:2022-08-11 16:11:31
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI; public class ImageTest : MonoBehaviour
{
/// <summary>
/// Image控件
/// </summary>
private Image image; void Start()
{
image = this.transform.Find("Image").GetComponent<Image>(); //为不同的按钮绑定不同的事件
this.transform.Find("LoadByWWW").GetComponent<Button>().onClick.AddListener
(
delegate () { LoadByWWW(); }
); this.transform.Find("LoadByIO").GetComponent<Button>().onClick.AddListener
(
delegate () { LoadByIO(); }
);
} /// <summary>
/// 以IO方式进行加载
/// </summary>
private void LoadByIO()
{
// double startTime = (double)Time.time;
//创建文件读取流
FileStream fileStream = new FileStream(Application.dataPath+ "/UI/Basic Information/Common/Add.png", FileMode.Open, FileAccess.Read);
fileStream.Seek(, SeekOrigin.Begin);
//创建文件长度缓冲区
byte[] bytes = new byte[fileStream.Length];
//读取文件
fileStream.Read(bytes, , (int)fileStream.Length);
//释放文件读取流
fileStream.Close();
fileStream.Dispose();
fileStream = null; //创建Texture
int width = ;
int height = ;
Texture2D texture = new Texture2D(width, height);
texture.LoadImage(bytes); //创建Sprite
Sprite sprite = Sprite.Create(texture, new Rect(, , texture.width, texture.height), new Vector2(0.5f, 0.5f));
image.sprite = sprite; //startTime = (double)Time.time - startTime;
//Debug.Log("IO加载用时:" + startTime);
} /// <summary>
/// 以WWW方式进行加载
/// </summary>
private void LoadByWWW()
{
StartCoroutine(Load());
} IEnumerator Load()
{
double startTime = (double)Time.time;
//请求WWW
//WWW www = new WWW("file://D:\\test.jpg");
string path= (Application.dataPath + "/UI/Basic Information/Common/Add.png");
WWW www=new WWW("file://"+path);
yield return www;
if (www != null && string.IsNullOrEmpty(www.error))
{
//获取Texture
Texture2D texture = www.texture; //创建Sprite
Sprite sprite = Sprite.Create(texture, new Rect(, , texture.width, texture.height), new Vector2(0.5f, 0.5f));
image.sprite = sprite; startTime = (double)Time.time - startTime;
Debug.Log("WWW加载用时:" + startTime);
}
}
} 原文链接http://blog.csdn.net/qinyuanpei/article/details/48262583