一、設定圖片存放的位置
二、檢查圖片是否要下載或是讀取
//指定到對應環境的路徑
public class utilPath
{
#if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN)
public static string LOCAL_PATH = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
#elif (UNITY_ANDROID)
public static string LOCAL_PATH = Application.persistentDataPath;
#endif
}
//設定要存放的路徑(ImageCache跟Image可以自定義名稱)
public string path
{
#if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN)
get { return utilPath.LOCAL_PATH + "\\ImageCache\\"; }
#elif (UNITY_ANDROID)
get { return utilPath.LOCAL_PATH + "/Image/"; }
#endif
}
public void SetAsyncImage(string mPath ,string imageName, UITexture bantexture)
{
//下載的url路徑
url = mPath;
//檢查檔案是否存在 (bantexture 畫面中顯示圖片的物件)
if (!File.Exists(path + imageName))
StartCoroutine(DownloadImage(imageName, bantexture));
else
StartCoroutine(LoadLocalImage(imageName, bantexture));
}
三、下載圖片
IEnumerator DownloadImage(string imageName, UITexture bantexture)
{
//url跟imageName是網路上的路徑跟圖檔名稱(ex:http://127.0.0.1/image/apple.jpg)
WWW www = new WWW("http://" + url + imageName);
yield return www;
if (!string.IsNullOrEmpty(www.error))
bantexture.mainTexture = Resources.Load("Picture/error") as Texture;
else{
Texture2D tex2d = www.texture;
byte[] pngdata = tex2d.EncodeToJPG();
File.WriteAllBytes(path + imageName , pngdata); //寫入圖檔
bantexture.mainTexture = tex2d; //回傳給要顯示的物件
}
}
四、讀取圖片
IEnumerator LoadLocalImage(string name, UITexture bantexture)
{
string FilePath = "file:///" + path + name;
//本地端的檔案路徑
WWW www = new WWW(FilePath);
yield return www;
Texture2D tex2d = www.texture;
bantexture.mainTexture = tex2d;
}
以上就是下載&讀取圖片的使用,有問題的話歡迎底下留言!!!
沒有留言:
張貼留言