diff --git a/UnityHelper/Util/SpriteUtil.cs b/UnityHelper/Util/SpriteUtil.cs index e9aed0d..c678f39 100644 --- a/UnityHelper/Util/SpriteUtil.cs +++ b/UnityHelper/Util/SpriteUtil.cs @@ -84,6 +84,25 @@ public static Sprite LoadSpriteFromArray(byte[] buffer, float pixelsPerUnit = 64 public static Sprite LoadSpriteFromArray(byte[] buffer, float pixelsPerUnit) => LoadSpriteFromArray(buffer, pixelsPerUnit, null); + /// + /// Converts the given 's alpha format to premultiplied. + /// The sprite's underlying texture must be readable. + /// + /// + /// If a sprite has a fuzzy white edge, or a white tint in areas where it's + /// partially transparent, running it through this function may fix the issue. + /// + /// + /// If the Sprite's underlying texture is not readable. + /// + /// The sprite to convert. + /// The same . + public static Sprite PremultiplyAlpha(this Sprite source) + { + source.texture.PremultiplyAlpha(); + return source; + } + #endregion #region Texture2D @@ -128,11 +147,38 @@ public static Texture2D LoadTextureFromFile(string fileName, bool makeUnreadable /// A object. public static Texture2D LoadTextureFromArray(byte[] buffer, bool makeUnreadable = false) { - Texture2D tex = new(2, 2); + // The texture format here doesn't matter, but this constructor can + // prevent textures from generating mipmaps. + Texture2D tex = new(2, 2, TextureFormat.RGBA32, mipChain: false); tex.LoadImage(buffer, makeUnreadable); return tex; } + /// + /// Converts the given 's alpha format to premultiplied. + /// The texture must be readable. + /// + /// + /// If a texture has a fuzzy white edge, or a white tint in areas where it's + /// partially transparent, running it through this function may fix the issue. + /// + /// If the texture is not readable. + /// The texture to convert. + /// The same . + public static Texture2D PremultiplyAlpha(this Texture2D source) + { + Color32[] pixels = source.GetPixels32(); + + for (int i = 0; i < pixels.Length; i++) { + Color px = pixels[i]; + pixels[i] = new Color(px.r * px.a, px.g * px.a, px.b * px.a, px.a); + } + + source.SetPixels32(pixels); + source.Apply(); + return source; + } + /// /// If the given texture is unreadable, returns a readable copy of it. /// If the given texture is readable, returns the same texture object. @@ -152,7 +198,7 @@ public static Texture2D GetReadableTexture(Texture2D tex) { var previous = RenderTexture.active; RenderTexture.active = temp; - var readable = new Texture2D(tex.width, tex.height); + var readable = new Texture2D(tex.width, tex.height, tex.format, mipChain: tex.mipmapCount > 1); readable.ReadPixels(new Rect(0, 0, temp.width, temp.height), 0, 0); readable.Apply();