当前位置:   article > 正文

Unity 加载网络图片_fresco unity

fresco unity

       IOS工程师都应该用过SDWebImage或者android工程师应该使用过Glide,fresco,Imageloader等,在Unity里面,我按照同样的原理封装了一个ImageLoader 。

原理就是先用一张placeholder来显示图片,等待图片加载,等加载完了之后替换placeholder,第二次加载网络图片时,先判断本地时候已经加载过图片,如果加载过就从本地获取图片,如果没有就去网络上加载。

下面代码:

  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using System.Collections;
  4. using System.IO;
  5. public class AsyncImageDownload : MonoBehaviour
  6. {
  7. public Sprite placeholder;
  8. private static AsyncImageDownload _instance = null;
  9. public static AsyncImageDownload GetInstance() { return Instance; }
  10. public static AsyncImageDownload Instance
  11. {
  12. get
  13. {
  14. if(_instance==null)
  15. {
  16. GameObject obj = new GameObject("AsyncImageDownload");
  17. _instance = obj.AddComponent<AsyncImageDownload>();
  18. DontDestroyOnLoad(obj);
  19. _instance.Init();
  20. }
  21. return _instance;
  22. }
  23. }
  24. public bool Init()
  25. {
  26. if (!Directory.Exists(Application.persistentDataPath + "/ImageCache/"))
  27. {
  28. Directory.CreateDirectory(Application.persistentDataPath + "/ImageCache/");
  29. }
  30. if(placeholder==null)
  31. {
  32. placeholder = Resources.Load("placeholder") as Sprite;
  33. }
  34. return true;
  35. }
  36. public void SetAsyncImage(string url, Image image)
  37. {
  38. //开始下载图片前,将UITexture的主图片设置为占位图
  39. image.sprite = placeholder;
  40. //判断是否是第一次加载这张图片
  41. if (!File.Exists(path + url.GetHashCode()))
  42. {
  43. //如果之前不存在缓存文件
  44. StartCoroutine(DownloadImage(url, image));
  45. }
  46. else {
  47. StartCoroutine(LoadLocalImage(url, image));
  48. }
  49. }
  50. IEnumerator DownloadImage(string url, Image image)
  51. {
  52. Debug.Log("downloading new image:" + path + url.GetHashCode());//url转换HD5作为名字
  53. WWW www = new WWW(url);
  54. yield return www;
  55. Texture2D tex2d = www.texture;
  56. //将图片保存至缓存路径
  57. byte[] pngData = tex2d.EncodeToPNG();
  58. File.WriteAllBytes(path + url.GetHashCode(), pngData);
  59. Sprite m_sprite = Sprite.Create(tex2d, new Rect(0, 0, tex2d.width, tex2d.height), new Vector2(0, 0));
  60. image.sprite = m_sprite;
  61. }
  62. IEnumerator LoadLocalImage(string url, Image image)
  63. {
  64. string filePath = "file:///" + path + url.GetHashCode();
  65. Debug.Log("getting local image:" + filePath);
  66. WWW www = new WWW(filePath);
  67. yield return www;
  68. Texture2D texture = www.texture;
  69. Sprite m_sprite = Sprite.Create(texture,new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0));
  70. image.sprite = m_sprite;
  71. }
  72. public string path
  73. {
  74. get
  75. {
  76. //pc,ios //android :jar:file//
  77. return Application.persistentDataPath + "/ImageCache/";
  78. }
  79. }
  80. }
End

.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/103531
推荐阅读
相关标签
  

闽ICP备14008679号