Unity WWW类缓存图片
发表于2018-04-26
大家做需求的时候,有时候会碰到需要去请求好友的头像的情况,可能很多人首先想到的是用uniy 的WWW.LoadFromCacheOrDownload函数,但很有可能出现:WWWCached data can only be accessed using the assetBundle property!的情况,所以本篇文章就教大家用WWW下载缓存图片。
实现方法如下:
1.判断是否已经加载过图片。
2.如果图片未加载过,从网上下载。
3.如果图片加载过了,从文件中下载。
下面给出自用代码:
if (!completedLoadThumbnail && !string.IsNullOrEmpty (mKakaoFriendData. fInfo.profile_thumbnail_image )) { if (!File .Exists( Application.dataPath + "/Resources/My/" + mKakaoFriendData.fInfo .profile_thumbnail_image. GetHashCode())) { StartCoroutine(LoadThumbnail (mKakaoFriendData. fInfo.profile_thumbnail_image )); } else { StartCoroutine(LoadLocalImage (mKakaoFriendData. fInfo.profile_thumbnail_image )); } }
private IEnumerator LoadThumbnail (string url) { WWW www = new WWW((new Uri(url)).AbsoluteUri); yield return www; if (!string .IsNullOrEmpty( www.error )) { Debug.Log (string. Format("Failed to load image: {0}, {1}" , url, www.error)); yield break ; } Texture2D image = www.texture; // 将图片保存至缓存路径 byte[] pngData = image.EncodeToPNG(); File.WriteAllBytes (Application. dataPath + "/Resources/My/" + url.GetHashCode(), pngData); mthumbnailImage.mainTexture = www.texture; completedLoadThumbnail = true ; }
private IEnumerator LoadLocalImage (string url) { // 已在本地缓存 string filePath = "file:///" + Application.dataPath + "/Resources/My/" + url.GetHashCode (); WWW www = new WWW(filePath); yield return www; mthumbnailImage.mainTexture = www.texture; completedLoadThumbnail = true ; }