看到草羊發的圖片,也是真懶。
想起來當時寫天氣預報現在都忘干凈了,好記性不如爛筆頭,還是應該多記。自己打下來好了
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.IO; public class readPictures : MonoBehaviour { private Image image; private string loadpath = "D:/SOmeOther/NGUI/Assets/StreamingAssets/test.jpg"; //IO方式加載的路徑 private string picpathWWW = "test.jpg"; //WWW的加載方式路徑 // Use this for initialization private void Start() { image = GetComponent<Image>(); //IO方法加載速度快 // LoadByIO(); //WWW 加載速度慢 LoadByWWW(); } private void LoadByIO() { double startTime = (double) Time.time; //創建文件流 FileStream fileStream = new FileStream(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 = new Texture2D(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 void LoadByWWW() { 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 就加載網絡圖片了 private IEnumerator Load() { double startTime = (double) Time.time; WWW www = new WWW(url + picpathWWW);//只能放URL // WWW www = new WWW(url);//只能放URL 這里可以換做網絡的URL yield return www; 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); } } }