当前位置 : 主页 > 手机开发 > harmonyos >

Unity 异步加载和保存图片避免主线程卡顿

来源:互联网 收集:自由互联 发布时间:2023-12-16
using System.IO;using System.Threading.Tasks;using UnityEngine;using UnityEngine.Experimental.Rendering;using UnityEngine.Networking;namespace Mx.Utils{ /// summary图像工具类/summary public class ImagesUtil { /// summary加载图片/su


using System.IO;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Networking;

namespace Mx.Utils
{
    /// <summary>图像工具类</summary>
    public class ImagesUtil
    {
        /// <summary>加载图片</summary>
        public static async Task<Texture2D> LoadImageAsync(string path)
        {
            using (UnityWebRequest www = UnityWebRequestTexture.GetTexture(path))
            {
                var asyncOperation = www.SendWebRequest();
                while (!asyncOperation.isDone)
                {
                    await Task.Delay(100);
                }

                if (www.result != UnityWebRequest.Result.Success)
                {
                    Debug.LogError("Failed to load image: " + www.error);
                    return null;
                }

                return DownloadHandlerTexture.GetContent(www);
            }
        }

        /// <summary>写入图片</summary>
        public static async Task WriteImageAsync(string filePath, Texture2D texture2D)
        {
            if (texture2D == null) return;

            GraphicsFormat graphicsFormat = GraphicsFormat.R8G8B8A8_UNorm;

            uint width = (uint)texture2D.width;
            uint height = (uint)texture2D.height;

            Color32[] array = texture2D.GetPixels32();

            await Task.Run(() =>
            {
                File.WriteAllBytes(filePath, ImageConversion.EncodeArrayToPNG(array, graphicsFormat, width, height));
            });
        }

    }
}
上一篇:Unity空间中移动物体
下一篇:没有了
网友评论