UGUI从服务器下载图片显示

using System.Collections;
using System.IO;
using UnityEngine.Networking;

namespace UnityEngine.UI
{
    [ExecuteInEditMode, RequireComponent(typeof(Image))]
    public class HttpImage : MonoBehaviour
    {
        private readonly string Url = "https://pic.feizl.com/upload/allimg/170705/";

        private readonly string ExtraFolder = "/Image";

        [SerializeField] private bool nativeSize = false;

        private Image image;

        private string key;

        private string url = "";

        private Coroutine coroutine;

        private void Awake()
        {
            image = GetComponent<Image>();
        }

        [ContextMenu("Test")]
        private void Test()
        {
            SetImage("0553tbupe1myfsw.jpg");
        }

        /// <summary>
        /// 设置图片
        /// </summary>
        /// <param name="key">名称</param>
        /// <param name="url">地址</param>
        /// <param name="extra">额外路径信息</param>
        public void SetImage(string key, string url = "", string extra = "")
        {
            if (string.IsNullOrEmpty(key)) return;

            if (this.key == key) return;

            string[] _temp = key.Split('/');

            this.key = _temp[_temp.Length - 1];

            this.url = string.IsNullOrEmpty(url) ? Url : url;

            this.url += extra;

            if (File.Exists(LocalPath))
            {
                SetImage(CreateSprite(Read()));
            }
            else
            {
                coroutine = StartCoroutine(Dowmload());
            }
        }

        IEnumerator Dowmload()
        {
            UnityWebRequest request = UnityWebRequestTexture.GetTexture(ServerPath);

            yield return request.SendWebRequest();

            if (request.isHttpError || request.isNetworkError)
            {
                Debug.LogError("Download Fail!!!");
            }
            else
            {
                if (request.isDone)
                {
                    Write(request.downloadHandler.data);
                    SetImage(CreateSprite(request.downloadHandler.data));
                }
            }
        }

        private Sprite CreateSprite(byte[] buffer)
        {
            Texture2D texture = new Texture2D(10, 10);
            texture.LoadImage(buffer);
            return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
        }

        private byte[] Read()
        {
            return File.ReadAllBytes(LocalPath);
        }

        private void Write(byte[] buffer)
        {
            if (Directory.Exists(Application.persistentDataPath + ExtraFolder) == false)
                Directory.CreateDirectory(Application.persistentDataPath + ExtraFolder);
            File.WriteAllBytes(LocalPath, buffer);
        }

        private void SetImage(Sprite sprite)
        {
            if (image != null)
            {
                image.overrideSprite = sprite;
                if (nativeSize)
                    image.SetNativeSize();
            }
        }

        private string LocalPath
        {
            get
            {
                return string.Format("{0}{1}/{2}", Application.persistentDataPath, ExtraFolder, key);
            }
        }

        private string ServerPath
        {
            get
            {
                return url + key;
            }
        }

        private void OnDisable()
        {
            if (coroutine != null)
            {
                StopCoroutine(coroutine);
            }
        }
    }
}
View Code

1. 设置图片key,及下载地址url

2. 判断是否本地已经下载图片【可通过MD5计算文件防止文件有重名Key】

3. 通过UnityWebRequest下载图片,并保存在本地

原文地址:https://www.cnblogs.com/Joke-crazy/p/12737411.html