Files
webRtc/Assets/Script/Util/WebRTCUtil.cs

81 lines
2.5 KiB
C#
Raw Normal View History

2026-05-19 22:40:52 +08:00
using System;
2026-05-22 10:59:18 +08:00
using System.Collections.Generic;
2026-05-19 22:40:52 +08:00
using System.IO;
2026-05-22 10:59:18 +08:00
using Cysharp.Threading.Tasks;
2026-05-19 22:40:52 +08:00
using Stary.Evo;
using UnityEngine;
using UnityEngine.UI;
using Random = UnityEngine.Random;
namespace Script.Util
{
public static class WebRTCUtil
{
2026-05-22 10:59:18 +08:00
public static Dictionary<string, Sprite> _avatarCache = new();
2026-05-19 22:40:52 +08:00
public static Color GetRandomColor()
{
return new Color(
Random.Range(0.2f, 0.8f),
Random.Range(0.2f, 0.8f),
Random.Range(0.2f, 0.8f),
1f
);
}
2026-05-22 10:59:18 +08:00
public static async UniTask DownloadAndSetAvatar(string avatarUrl, Image targetImage)
2026-05-19 22:40:52 +08:00
{
try
{
2026-05-22 10:59:18 +08:00
if (_avatarCache.TryGetValue(avatarUrl, out var sprite))
{
targetImage.sprite = sprite;
return;
}
2026-05-19 22:40:52 +08:00
var tempPath = Path.Combine(Application.temporaryCachePath, $"avatar_{Guid.NewGuid()}.png");
var result = await WebRequestSystem.GetFile(avatarUrl, tempPath);
if (result.code == 200)
{
var bytes = File.ReadAllBytes(tempPath);
var texture = new Texture2D(2, 2);
texture.LoadImage(bytes);
2026-05-22 10:59:18 +08:00
sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height),
2026-05-19 22:40:52 +08:00
Vector2.one * 0.5f);
targetImage.sprite = sprite;
File.Delete(tempPath);
2026-05-22 10:59:18 +08:00
_avatarCache.TryAdd(avatarUrl, sprite);
2026-05-19 22:40:52 +08:00
}
}
catch (Exception e)
{
Debug.LogError($"下载头像失败: {e.Message}");
}
}
2026-05-22 15:43:00 +08:00
/// <summary>
/// 尝试将dataUrl解码为Texture2D
/// </summary>
/// <param name="dataUrl"></param>
/// <param name="tex"></param>
/// <returns></returns>
public static bool TryDecodeDataUrlToTexture(string dataUrl, out Texture2D tex)
{
tex = null;
if (string.IsNullOrEmpty(dataUrl)) return false;
if (!dataUrl.StartsWith("data:image/")) return false;
var comma = dataUrl.IndexOf(',');
if (comma < 0) return false;
var b64 = dataUrl.Substring(comma + 1);
var bytes = Convert.FromBase64String(b64);
tex = new Texture2D(2, 2, TextureFormat.RGBA32, false);
return tex.LoadImage(bytes);
}
2026-05-19 22:40:52 +08:00
}
}