using System; using System.Collections.Generic; using System.IO; using Cysharp.Threading.Tasks; using Stary.Evo; using UnityEngine; using UnityEngine.UI; using Random = UnityEngine.Random; namespace Script.Util { public static class WebRTCUtil { public static Dictionary _avatarCache = new(); 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 ); } public static async UniTask DownloadAndSetAvatar(string avatarUrl, Image targetImage) { try { if (_avatarCache.TryGetValue(avatarUrl, out var sprite)) { targetImage.sprite = sprite; return; } 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); sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.one * 0.5f); targetImage.sprite = sprite; File.Delete(tempPath); _avatarCache.TryAdd(avatarUrl, sprite); } } catch (Exception e) { Debug.LogError($"下载头像失败: {e.Message}"); } } /// /// 尝试将dataUrl解码为Texture2D /// /// /// /// 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); } } }