public Sprite sp;
IEnumerator loadSprite(string path)
{
string filePath = path;
WWW www = new WWW(filePath);
yield return www;
Texture2D texture = www.texture;
sp = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}
}
這樣,我們就能将本地圖檔加載到sp裡面,通過觀察者模式,可以動态顯示圖檔。
示例程式:
// Use this for initialization
void Start () {
StartCoroutine(loadSprite("file://" +"C:\\Users\\HP\\Desktop\\相冊\\合照\\IMG_7438.jpg"));
}
public Image img;
// Update is called once per frame
void Update () {
}
public Sprite sp;
IEnumerator loadSprite(string path)
{
string filePath = path;
WWW www = new WWW(filePath);
yield return www;
Texture2D texture = www.texture;
//因為我們定義的是Image,是以這裡需要把Texture2D轉化為Sprite
sp = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
img.sprite = sp;
}
需要注意,在pc端,需要加上
"file://"
字首