Skip to content

Commit

Permalink
perf: optimize opacity filter allocations
Browse files Browse the repository at this point in the history
  • Loading branch information
ramezgerges committed Oct 17, 2024
1 parent 449a174 commit 91be36d
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/Uno.UI.Composition/Composition/Uno/DrawingFilter.skia.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System;
using System.Linq;
using SkiaSharp;
using Uno.Extensions;

namespace Uno.UI.Composition;

Expand All @@ -13,15 +14,21 @@ namespace Uno.UI.Composition;
/// The opacity to apply to children.
/// This should be applied only on drawing and not the container to avoid fade-ou of child containers.
/// </param>
internal record struct DrawingFilters(float Opacity)
internal readonly record struct DrawingFilters(float Opacity)
{
public static DrawingFilters Default { get; } = new(1.0f);

private SKColorFilter? _opacityColorFilter = null;

// Note: This SKColorFilter might be created more than once since this Filter is a struct.
// However since this Filter is copied (pushed to the stack) only when something changes, it should still catch most cases.
public SKColorFilter? OpacityColorFilter => Opacity is 1.0f
? null
: _opacityColorFilter ??= SKColorFilter.CreateBlendMode(new SKColor(0xFF, 0xFF, 0xFF, (byte)(255 * Opacity)), SKBlendMode.Modulate);
: _opacityToColorFilter.Invoke((byte)(255 * Opacity));

// only 255 possible values
private static readonly Func<byte, SKColorFilter> _opacityToColorFilter = FuncMemoizeExtensions.AsMemoized((byte opacity)
=>
{
Console.WriteLine($"Ramez created a new color filter for opacity {opacity}");
return SKColorFilter.CreateBlendMode(new SKColor(0xFF, 0xFF, 0xFF, opacity), SKBlendMode.Modulate);
});
}

0 comments on commit 91be36d

Please sign in to comment.