unity讀取Texture文件並轉為Sprit


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(0, SeekOrigin.Begin);
        //創建文件長度緩沖區
        byte[] bytes = new byte[fileStream.Length];
        //讀取文件
        fileStream.Read(bytes, 0, (int)fileStream.Length);
        //釋放文件讀取流
        fileStream.Close();
        fileStream.Dispose();
        fileStream = null;

        //創建Texture
        int width = 300;
        int height = 372;
        Texture2D texture = new Texture2D(width, height);
        texture.LoadImage(bytes);

        //創建Sprite
        Sprite sprite = Sprite.Create(texture, new Rect(0, 0, 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(0, 0, 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM