当前位置:   article > 正文

基于Unity UGUI RawImage的网络头像功能实现方案_unity中如何给image赋值网络头像

unity中如何给image赋值网络头像

实现类似排行版、社交模块的头像下载与管理的封装,使用者只需要对控件进行图片网络地址的设置就能完成图片刷新。为了方便,代码全写在一个脚本,需要的自己整合一下。

使用方法:将脚本挂载到RawImage控件,调用SetOnlineTexture方法,传入图片网路地址即可。

  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.UI;
  4. using System;
  5. using System.Collections.Generic;
  6. [RequireComponent(typeof(RawImage))]
  7. public class ImageDownloader : MonoBehaviour
  8. {
  9. private static Dictionary<string,Texture2D> mImageCacheDict = new Dictionary<string, Texture2D>();
  10. private RawImage mImage;
  11. void Awake()
  12. {
  13. mImage = GetComponent<RawImage>();
  14. //Test
  15. //SetOnlineTexture("http://thirdwx.qlogo.cn/mmopen/vi_32/ceXE8MaLuaThTbb3hibXvcoq6q3tt7APnP5GicHY6caYkYa86sVBMhH7JKQJICfWlsD4PTWlM3iaKXjdoM5gp1Ddg/96");
  16. }
  17. public void SetOnlineTexture(string mUrl)
  18. {
  19. Action<bool,Texture2D> handle = (bool mIsSuccess, Texture2D mSetupTexture) =>
  20. {
  21. if (mIsSuccess)
  22. {
  23. mImage.texture = mSetupTexture;
  24. }
  25. else
  26. {
  27. //TODO 加载失败处理
  28. }
  29. };
  30. Texture2D mTexture;
  31. if (TryGetImageInCache(mUrl, out mTexture))
  32. {
  33. handle(true, mTexture);
  34. }
  35. else
  36. {
  37. StartCoroutine(DownLoadImages(mUrl, handle));
  38. }
  39. }
  40. IEnumerator DownLoadImages(string mUrl, Action<bool, Texture2D> mCallBack)
  41. {
  42. WWW www = new WWW(mUrl);
  43. while (!www.isDone)
  44. {
  45. yield return null;
  46. }
  47. if (string.IsNullOrEmpty(www.error))
  48. {
  49. UpdateImageInCache(mUrl, www.texture);
  50. mCallBack(true, www.texture);
  51. }
  52. else
  53. {
  54. mCallBack(false, null);
  55. }
  56. www.Dispose();
  57. yield return null;
  58. }
  59. public static bool TryGetImageInCache(string mPath, out Texture2D mTexture)
  60. {
  61. return mImageCacheDict.TryGetValue(mPath, out mTexture);
  62. }
  63. public static void UpdateImageInCache(string mPath, Texture2D mTexture)
  64. {
  65. if (mImageCacheDict.ContainsKey(mPath))
  66. {
  67. mImageCacheDict[mPath] = mTexture;
  68. }
  69. else
  70. {
  71. mImageCacheDict.Add(mPath, mTexture);
  72. }
  73. }
  74. }

 

 

 


 

 

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

闽ICP备14008679号