Files
TaiWan/Assets/Roaming/Scripts/Loader/ImageLoader.cs
2025-10-31 15:20:38 +08:00

219 lines
6.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using DG.Tweening;
using static UnityEngine.Rendering.DebugUI;
/// <summary>
/// 图片加载器
/// </summary>
public class ImageLoader<T> : MonoBehaviour
{
public static Dictionary<string, Texture2D> dicTextures;
static List<string> removeKeys;
static Image progress;
static ImageLoader()
{
dicTextures = new Dictionary<string, Texture2D>();
removeKeys = new List<string>();
if(progress==null) progress = GameObject.Find("progress").GetComponent<Image>();
}
public static void RemoveTexture()
{
if (removeKeys.Count > 0)
{
if (dicTextures.ContainsKey(removeKeys[0]))
{
Destroy(dicTextures[removeKeys[0]]);
dicTextures.Remove(removeKeys[0]);
Resources.UnloadUnusedAssets();
}
Debug.Log("Removed:" + removeKeys[0]);
removeKeys.RemoveAt(0);
}
}
#region
///// <summary>
///// 从外部指定文件中加载图片
///// </summary>
///// <param name="imgFullName">文件路径</param>
///// <returns></returns>
//public static Texture2D LoadTextureByIO(string imgFullName)
//{
// FileStream fs = new FileStream(imgFullName, FileMode.Open, FileAccess.Read);
// fs.Seek(0, SeekOrigin.Begin);//游标的操作,可有可无
// byte[] bytes = new byte[fs.Length];//生命字节,用来存储读取到的图片字节
// try
// {
// fs.Read(bytes, 0, bytes.Length);//开始读取这里最好用trycatch语句防止读取失败报错
// }
// catch (System.Exception e)
// {
// Debug.Log(e);
// }
// fs.Close();//切记关闭
// int width = 2048;//图片的宽(这里两个参数可以提到方法参数中)
// int height = 2048;//图片的高这里说个题外话pico相关的开发这里不能大于4k×4k不然会显示异常当时开发pico的时候应为这个问题找了大半天原因因为美术给的图是6000*3600导致出现切几张图后就黑屏了。。。
// Texture2D texture = new Texture2D(width, height);
// if (texture.LoadImage(bytes))
// {
// //print("图片加载完毕 ");
// return texture;
// }
// else
// {
// //print("图片尚未加载");
// return null;
// }
//}
#endregion
/// <summary>
/// 协程加载图像
/// </summary>
/// <param name="imgFullName">图像名</param>
/// <param name="mat">材质对象</param>
public static IEnumerator LoadImage(string imgFullName, T mat, ImageLoadedEventHandler<T> ImageLoaded = null)
{
// Debug.Log(imgFullName);
//progress.gameObject.SetActive(true);
DOTween.KillAll();
progress.fillAmount = 0;
Texture2D tex = null;
if (dicTextures.ContainsKey(imgFullName))
{
tex = dicTextures[imgFullName];
}
else
{
UnityWebRequest www = UnityWebRequestTexture.GetTexture(imgFullName);
yield return www.SendWebRequest();
// Debug.Log($"下载{imgFullName}进度:{www.downloadProgress}");
//while (!www.isDone)
//{
// yield return null;
// //GameObject.Find("progress").GetComponent<LoadProgress>().loadWebRequest = www;
// DOTween.To(() => progress.fillAmount, x => progress.fillAmount = x, www.downloadProgress, Time.deltaTime).OnComplete(() =>
// {
// if (progress.fillAmount >= 0.99)
// {
// DOTween.KillAll();
// progress.fillAmount = 0;
// }
// });
// //Tweener tweener = DOTween.To(() => progress.fillAmount, x=> progress.fillAmount, www.downloadProgress,Time.deltaTime);
// //progress.fillAmount = www.downloadProgress;
// //progress.fillAmount = Mathf.Lerp(progress.fillAmount, www.downloadProgress,Time.deltaTime);
// Debug.Log(www.downloadProgress);
//}
//DOTween.KillAll(); progress.fillAmount = 0;
//DOTween.To(() => progress.fillAmount, x => progress.fillAmount = x, 0, 0);
if (www.result == UnityWebRequest.Result.ConnectionError)
{
Debug.Log(www.error);
}
else
{
//progress.gameObject.SetActive(false);
try
{
tex = ((DownloadHandlerTexture)www.downloadHandler).texture;
if (!dicTextures.ContainsKey(imgFullName))
{
dicTextures.Add(imgFullName, tex);
}
}
catch
{
Debug.Log("图片加载失败:" + imgFullName);
}
}
www.Dispose();
}
if (ImageLoaded == null)
{
ImageLoaded = DefaultImageLoaded;
}
ImageLoaded(tex, mat);
}
public static void DefaultImageLoaded(Texture2D tex, T mat)
{
if (mat != null)
{
if (mat is Material)
{
Material matTmp = mat as Material;
// 更新材质
matTmp.mainTexture = tex;
if (matTmp.IsKeywordEnabled("_EMISSION"))
{
matTmp.SetTexture("_EmissionMap", tex);
}
}
else if (mat is RawImage)
{
RawImage matTmp = mat as RawImage;
matTmp.texture = tex;
}
else if (mat is Image)
{
Image matTmp = mat as Image;
matTmp.sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), Vector2.zero);
}
// ClearImage();
}
}
public static void RemoveImage(string imageName)
{
// removeKeys.Add(imageName);
// Debug.Log("Remove:" + imageName);
if (dicTextures.ContainsKey(imageName))
{
Destroy(dicTextures[imageName]);
dicTextures.Remove(imageName);
}
// Resources.UnloadUnusedAssets();
}
public static void ClearImage()
{
foreach (string key in dicTextures.Keys)
{
Destroy(dicTextures[key]);
}
dicTextures.Clear();
}
//回收内存的协程
IEnumerator ToDestoryThis(Texture2D thisSprite)
{
yield return new WaitForSeconds(0.1f);
//Destroy(thisSprite);
Resources.UnloadUnusedAssets();//卸载未占用的asset资源
System.GC.Collect();//回收内存
}
}
/// <summary>
/// 图片加载结束事件委托
/// </summary>
/// <param name="tex">图片对象</param>
public delegate void ImageLoadedEventHandler<T>(Texture2D tex, T mat);