当前位置:   article > 正文

Unity中使用UnityWebRequest进行网络和本地图片加载_unity中加载网络图片资源

unity中加载网络图片资源

在实际项目中,往往会有一些需求是要从网络上加载图片展示出来。例如玩家的头像,公告大图和一些需要加载的展示的图片,这时就需要用代码实现从网络上加载必要的图片资源。

更新迭代版本的Unity已经在逐步放弃对WWW的支持,推出UnityWebRequest,详见Unity资源存放与加载-本地资源 更新资源

UnityWebRequest同时也支持AssetsBundle,xml等文件资源的下载。

本文在基于UnityWebRequest的基础上,实现网络图片和本地磁盘图片的加载,并且实现在屏幕上。

先看看使用WWW是怎么完成图片加载的:

  1. using (WWW www = new WWW(url))
  2. {
  3. yield return www;
  4. if (string.IsNullOrEmpty(www.error))
  5. {
  6. //获取到链接中的图片
  7. Texture2D texture = www.texture;
  8. }
  9. }

这段代码比较简单,返回的www.texture就是链接图片,这样就完成了简单的图片加载了。

但是,实际上,通常需要将图片加载内存和缓存到本地,以便在下一次可以很快的加载,而不用再次从网络上拉取。

流程:                                                                                   

关键代码:github地址

  1. ///LoadImageMgr.cs
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using System;
  6. using System.IO;
  7. using UnityEngine.Networking;
  8. public class LoadImageMgr
  9. {
  10. /// <summary>
  11. /// download from web or hard disk
  12. /// </summary>
  13. /// <param name="url"></param>
  14. /// <param name="loadEnd">callback</param>
  15. /// <returns></returns>
  16. public IEnumerator LoadImage(string url, Action<Texture2D> loadEnd)
  17. {
  18. Texture2D texture = null;
  19. //先从内存加载
  20. if (imageDic.TryGetValue(url,out texture))
  21. {
  22. loadEnd.Invoke(texture);
  23. yield break;
  24. }
  25. string savePath = GetLocalPath();
  26. string filePath = string.Format("file://{0}/{1}.png", savePath, UnityUtil.MD5Encrypt(url));
  27. //from hard disk
  28. bool hasLoad = false;
  29. if (Directory.Exists(filePath))
  30. yield return DownloadImage(filePath, (state, localTexture) =>
  31. {
  32. hasLoad = state;
  33. if (state)
  34. {
  35. loadEnd.Invoke(localTexture);
  36. if (!imageDic.ContainsKey(url))
  37. imageDic.Add(url, localTexture);
  38. }
  39. });
  40. if (hasLoad) yield break; //loaded
  41. //from web
  42. yield return DownloadImage(url, (state, downloadTexture) =>
  43. {
  44. hasLoad = state;
  45. if (state)
  46. {
  47. loadEnd.Invoke(downloadTexture);
  48. if (!imageDic.ContainsKey(url))
  49. imageDic.Add(url, downloadTexture);
  50. Save2LocalPath(url, downloadTexture);
  51. }
  52. });
  53. }
  54. public IEnumerator DownloadImage(string url, Action<bool, Texture2D> downloadEnd)
  55. {
  56. using (UnityWebRequest request = new UnityWebRequest(url))
  57. {
  58. DownloadHandlerTexture downloadHandlerTexture = new DownloadHandlerTexture(true);
  59. request.downloadHandler = downloadHandlerTexture;
  60. yield return request.Send();
  61. if (string.IsNullOrEmpty(request.error))
  62. {
  63. Texture2D localTexture = downloadHandlerTexture.texture;
  64. downloadEnd.Invoke(true, localTexture);
  65. }
  66. else
  67. {
  68. downloadEnd.Invoke(false, null);
  69. Debug.Log(request.error);
  70. }
  71. }
  72. }
  73. /// <summary>
  74. /// save the picture
  75. /// </summary>
  76. /// <param name="url"></param>
  77. /// <param name="texture"></param>
  78. private void Save2LocalPath(string url, Texture2D texture)
  79. {
  80. byte[] bytes = texture.EncodeToPNG();
  81. string savePath = GetLocalPath();
  82. try
  83. {
  84. File.WriteAllBytes( string.Format("{0}/{1}.png", savePath , UnityUtil.MD5Encrypt(url)), bytes);
  85. }
  86. catch(Exception ex)
  87. {
  88. Debug.LogError(ex.ToString());
  89. }
  90. }
  91. /// <summary>
  92. /// get which path will save
  93. /// </summary>
  94. /// <returns></returns>
  95. private string GetLocalPath()
  96. {
  97. string savePath = Application.persistentDataPath + "/pics";
  98. #if UNITY_EDITOR
  99. savePath = Application.dataPath + "/pics";
  100. #endif
  101. if (!Directory.Exists(savePath))
  102. {
  103. Directory.CreateDirectory(savePath);
  104. }
  105. return savePath;
  106. }
  107. private Dictionary<string, Texture2D> imageDic = new Dictionary<string, Texture2D>();
  108. public static LoadImageMgr instance { get; private set; } = new LoadImageMgr();
  109. }

 

  1. ///LoadImageHelper.cs
  2. using System;
  3. using System.Collections;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. public class LoadImageHelper : MonoBehaviour
  7. {
  8. string defaultUrl = "http://avatar.csdnimg.cn/1/E/6/2_u013012420.jpg";
  9. /// <summary>
  10. /// use this to load image
  11. /// </summary>
  12. /// <param name="texture"></param>
  13. /// <param name="url"></param>
  14. public void LoadImage(RawImage rawImage, string url)
  15. {
  16. if (string.IsNullOrEmpty(url))
  17. {
  18. url = defaultUrl;
  19. }
  20. StartCoroutine(LoadTeture(url, (tex) => {
  21. rawImage.texture = tex;
  22. }));
  23. }
  24. IEnumerator LoadTeture(string url, Action<Texture2D> cb)
  25. {
  26. yield return LoadImageMgr.instance.LoadImage(url, cb);
  27. }
  28. }

 

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

闽ICP备14008679号