Skip to content

Commit

Permalink
Merge pull request #111 from LingFeng-bbben/perf-spriteLoader
Browse files Browse the repository at this point in the history
Sync
  • Loading branch information
LeZi9916 authored Jan 20, 2025
2 parents a83c144 + cac8a0e commit 0c753e2
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions Assets/Script/Utils/SpriteLoader.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
using System;
using SkiaSharp;
using SkiaSharp.Unity;
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Http;
Expand Down Expand Up @@ -29,8 +32,7 @@ public static async Task<Sprite> LoadAsync(string path, CancellationToken ct = d
return Sprite.Create(new Texture2D(0, 0), new Rect(0, 0, 0, 0), new Vector2(0.5f, 0.5f));
var bytes = await File.ReadAllBytesAsync(path, ct);
ct.ThrowIfCancellationRequested();
var texture = new Texture2D(0, 0);
texture.LoadImage(bytes);
var texture = await ImageDecodeAsync(bytes);
return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}

Expand All @@ -39,7 +41,7 @@ public static async Task<Sprite> LoadAsync(Uri uri, CancellationToken ct = defau
Directory.CreateDirectory(MajEnv.CachePath);
var b64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(uri.OriginalString));
var cachefile = Path.Combine(MajEnv.CachePath, b64);
byte[] bytes;
byte[] bytes = Array.Empty<byte>();
if (!File.Exists(cachefile))
{
var client = new HttpClient(new HttpClientHandler() { Proxy = WebRequest.GetSystemWebProxy(), UseProxy = true });
Expand All @@ -52,8 +54,7 @@ public static async Task<Sprite> LoadAsync(Uri uri, CancellationToken ct = defau
bytes = await File.ReadAllBytesAsync(cachefile, ct);
}
ct.ThrowIfCancellationRequested();
var texture = new Texture2D(0, 0);
texture.LoadImage(bytes);
var texture = await ImageDecodeAsync(bytes);
return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}

Expand All @@ -67,5 +68,13 @@ public static Sprite Load(string path, Vector4 border)
return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100, 1,
SpriteMeshType.FullRect, border);
}
async static Task<Texture2D> ImageDecodeAsync(byte[] data)
{
using var bitmap = await Task.Run(() =>
{
return SKBitmap.Decode(data);
});
return bitmap.ToTexture2D();
}
}
}

0 comments on commit 0c753e2

Please sign in to comment.