Unity 加载网络图片


using UnityEngine;
using System.IO;
using UnityEngine.UI;
using System.Collections;

public class AsyncImageDownload : MonoBehaviour {
    public Sprite placeholder = null;

    private static AsyncImageDownload _instance = null;
    public static AsyncImageDownload GetInstance() { return Instance; }


    public string url = "";

    public Image image;
    public string path
    {
        get
        {
            return Application.persistentDataPath + "/ImageCache/";
        }
    }
    public static AsyncImageDownload Instance
    {
        get
        {
            if(_instance == null)
            {
                GameObject obj = new GameObject("AsyncImageLoad");
                _instance = obj.AddComponent<AsyncImageDownload>();
                DontDestroyOnLoad(obj);
                _instance.Init();
            }
            return _instance;
        }
    }


    void Start()
    {
        Init();
        SetAsyncImage(url, image);
    }

    void Update()
    {

    }

    public bool Init()
    {
        if(!Directory .Exists(Application .persistentDataPath + "/ImageCache/"))
        {
            Directory.CreateDirectory(Application.persistentDataPath + "/ImageCache/");
        }
        if(placeholder == null)
        {
            placeholder = Resources.Load("placeholder") as Sprite;
        }

        return true;
    }

    public void SetAsyncImage(string url, Image image)
    {
        image.sprite = placeholder;
        if(!File.Exists(path + url.GetHashCode()))
        {
            StartCoroutine(DownloadImage(url, image));
        }
        else
        {
            StartCoroutine(LoadLocalImage(url, image));
        }
    }

    private IEnumerator DownloadImage(string url, Image image)
    {
        Debug.Log("downloading new image :" + path + url.GetHashCode());
        WWW www = new WWW(url);
        yield return www;

        Texture2D tex2D = www.texture;

        byte[] pngData = tex2D.EncodeToPNG();
        File.WriteAllBytes(path + url.GetHashCode(), pngData);

        Sprite mSp = Sprite.Create(tex2D, new Rect(0, 0, tex2D.width, tex2D.height), new Vector2(0, 0));
        image.sprite = mSp;
    }

    private 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 mSp = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0));
        image.sprite = mSp;
    }
}


原文链接 : http://blog.csdn.net/yupu56/article/details/50915306


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值