using UnityEngine;
02.
using System.Collections;
03.
using System.IO;
04.
05.
public
class
AsyncImageDownload :MonoBehaviour {
06.
07.
public
Texture placeholder;
08.
public
static
AsyncImageDownload Instance=
null
;
09.
10.
private
string path=Application.persistentDataPath+
"/ImageCache/"
;
11.
12.
//构建单例
13.
public
static
AsyncImageDownload CreateSingleton()
14.
{
15.
if
(!Directory.Exists(Application.persistentDataPath+
"/ImageCache/"
)) {
16.
Directory.CreateDirectory(Application.persistentDataPath+
"/ImageCache/"
);
17.
}
18.
19.
GameObject obj =
new
GameObject ();
20.
obj.AddComponent<AsyncImageDownload> ();
21.
22.
AsyncImageDownload loader= obj.GetComponent<AsyncImageDownload>();
23.
Instance=loader;
24.
loader.placeholder=Resources.Load(
"placeholder"
) as Texture;
25.
return
loader;
26.
27.
}
28.
29.
30.
public
void
SetAsyncImage(string url,UITexture texture){
31.
32.
33.
34.
//开始下载图片前,将UITexture的主图片设置为占位图
35.
texture.mainTexture = placeholder;
36.
37.
//判断是否是第一次加载这张图片
38.
39.
if
(!File.Exists (path + url.GetHashCode())) {
40.
//如果之前不存在缓存文件
41.
42.
43.
StartCoroutine (DownloadImage (url, texture));
44.
45.
46.
}
47.
else
{
48.
49.
StartCoroutine(LoadLocalImage(url,texture));
50.
51.
}
52.
53.
}
54.
55.
IEnumerator DownloadImage(string url,UITexture texture){
56.
Debug.Log(
"downloading new image:"
+path+url.GetHashCode());
57.
WWW www =
new
WWW (url);
58.
yield
return
www;
59.
60.
Texture2D image = www.texture;
61.
//将图片保存至缓存路径
62.
byte
[] pngData = image.EncodeToPNG();
63.
File.WriteAllBytes(path+url.GetHashCode(), pngData);
64.
65.
texture.mainTexture = image;
66.
67.
}
68.
69.
IEnumerator LoadLocalImage(string url,UITexture texture){
70.
string filePath =
"file:///"
+ path + url.GetHashCode ();
71.
72.
Debug.Log(
"getting local image:"
+filePath);
73.
WWW www =
new
WWW (filePath);
74.
yield
return
www;
75.
76.
77.
//直接贴图
78.
texture.mainTexture = www.texture;
79.
80.
}
81.
}
1.最近我也碰到过这个问题,我是这样解决的。
1.将文件下载完成2.通过URL获取文件名字(类型包括在里面了)
3.通过字节的形式,以写文件的方式写到本地。
直接上代码:
private IEnumerator DownLoadToLocal(string url, string number)
{
WWW www = new WWW(url);
string img_name = url.Substring(url.LastIndexOf('/') + 1); //根据URL获取文件的名字。
yield return www;
if ( www.error == null)
{
FileStream fs = File.Create(path + img_name); //path为你想保存文件的路径。
fs.Write( www.bytes , 0, www.bytes.Length );
fs.Close();
}
else
{
Debug.Log( www.error );
}
}