在简书上看到了一个网友的分享,收藏一下 https://www.jianshu.com/p/8e461083879d
代码单独贴出来
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.IO;
using System.Collections.Generic;
public class AsyncImageDownload : MonoBehaviour
{
private Sprite placeholder;
private static List<string> files = null;
public void Start()
{
if (!Directory.Exists(Application.persistentDataPath + "/ImageCache/"))
{
Directory.CreateDirectory(Application.persistentDataPath + "/ImageCache/");
}
}
public void SetAsyncImage(string url, Image image)
{
//开始下载图片前,将UITexture的主图片设置为占位图
//image.sprite = placeholder;
//判断是否是第一次加载这张图片
if (!File.Exists(path + url.GetHashCode()))
{
if (files != null)
{
files.Add(url.GetHashCode().ToString());
}
else {
files = new List<string>();
files.Add(url.GetHashCode().ToString());
}
//如果之前不存在缓存文件
StartCoroutine(DownloadImage(url, image));
}
else
{
StartCoroutine(LoadLocalImage(url, image));
}
}
IEnumerator DownloadImage(string url, Image image)
{
Debug.Log("downloading new image:" + path + url.GetHashCode());//url转换HD5作为名字
WWW www = new WWW(url);
yield return www;
Texture2D tex2d = www.texture;
//将图片保存至缓存路径
byte[] pngData = tex2d.EncodeToPNG();
File.WriteAllBytes(path + url.GetHashCode(), pngData);
Sprite m_sprite = Sprite.Create(tex2d, new Rect(0, 0, tex2d.width, tex2d.height), new Vector2(0, 0));
image.sprite = m_sprite;
image.SetNativeSize();
}
IEnumerator LoadLocalImage(string url, Image image)
{
string filePath = "file:///" + path + url.GetHashCode();
Debug.Log("getting local image:" + filePath);
WWW www = new WWW(filePath);
yield return www;
Texture2D texture = www.texture;
Sprite m_sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0));
image.sprite = m_sprite;
image.SetNativeSize();
}
public string path
{
get
{
//pc,ios //android :jar:file//
return Application.persistentDataPath + "/ImageCache/";
}
}
public void OnDisable()
{
//CleanFiles();
}
public void OnDestroy()
{
CleanFiles();
}
public void CleanFiles() {
if (files != null && files.Count > 0) {
for (int i = files.Count - 1; i >= 0; i--) {
if (!Directory.Exists(path + files[i])) {
Debug.LogError("delete file path " + path + files[i]);
File.Delete(path + files[i]);
files.RemoveAt(i);
}
}
}
}
}