在http://www.tuicool.com/articles/ZFrMZnM的基础上对AsyncImageDownload进行了完善,完整代码如下:
using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System;
/// <summary>
/// 图片(Texture)加载类
/// 三级缓存:1、如果在内存中,则先从内存获取;2、没有则查看本地是否存在,存在则从本地获取;3、没有则再从网络进行获取并保存到本地。
/// </summary>
public class AsyncImageDownload : MonoBehaviour
{
/// <summary>
/// 默认图片
/// </summary>
public Texture placeholder;
/// <summary>
/// 单例
/// </summary>
public static AsyncImageDownload Instance = null;
/// <summary>
/// 本地图片保存路径。如果是android环境,Application.persistentDataPath值为/storage/emulated/legacy/Android/data/com.xxx.xxx/files/
/// </summary>
private string imageCacheRootPath = Application.persistentDataPath + "/ImageCache/";
/// <summary>
/// 缓存在内存里的texture,重复利用。key是url对应图片保存成本地文件的绝对路径。
/// texture采用弱引用方式,当系统需要回收时这里不会因为强引用阻止回收。
/// </summary>
private Dictionary<string, WeakReference> textureCache = new Dictionary<string,WeakReference>();
/// <summary>
/// 应用开始运行时,可以调用此方法进行初始化
/// </summary>
/// <returns>AsyncImageDownload单例对象</returns>
public static AsyncImageDownload CreateSingleton()
{
if (!Directory.Exists(Application.persistentDataPath + "/ImageCache/"))
{
Directory.CreateDirectory(Application.persistentDataPath + "/ImageCache/");
}
GameObject obj = new GameObject();
obj.AddComponent<AsyncImageDownload>();
AsyncImageDownload loader = obj.GetComponent<AsyncImageDownload>();
Instance = loader;
loader.placeholder = Resources.Load("default_cover") as Texture;// 默认图片
Debug.Log("image save path : "