Skip to content

Commit

Permalink
Cache icon paints by color
Browse files Browse the repository at this point in the history
  • Loading branch information
ScrubN committed Mar 26, 2024
1 parent 9f8098a commit 33b6dad
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions TwitchDownloaderCore/Tools/HighlightIcons.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using TwitchDownloaderCore.Options;
using TwitchDownloaderCore.TwitchObjects;
Expand Down Expand Up @@ -60,6 +62,7 @@ public sealed class HighlightIcons : IDisposable
private readonly double _fontSize;
private readonly bool _outline;
private readonly SKPaint _outlinePaint;
private readonly Dictionary<SKColor, SKPaint> _iconPaints = new();

public HighlightIcons(ChatRenderOptions renderOptions, SKColor iconPurple, SKPaint outlinePaint)
{
Expand Down Expand Up @@ -189,6 +192,7 @@ private SKImage GenerateGiftedManyIcon()

var imageInfo = new SKImageInfo(finalIconSize, finalIconSize);
using var resizedBitmap = tempBitmap.Resize(imageInfo, SKFilterQuality.High);

resizedBitmap.SetImmutable();
return SKImage.FromBitmap(resizedBitmap);
}
Expand All @@ -198,13 +202,10 @@ private SKImage GenerateSvgIcon(string iconSvgString, SKColor iconColor)
using var tempBitmap = new SKBitmap(ICON_SIZE, ICON_SIZE);
using var tempCanvas = new SKCanvas(tempBitmap);

var iconPaint = GetSvgIconPaint(iconColor);
using var iconPath = SKPath.ParseSvgPathData(iconSvgString);
iconPath.FillType = SKPathFillType.EvenOdd;

using var iconPaint = new SKPaint();
iconPaint.Color = iconColor;
iconPaint.IsAntialias = true;

if (_outline)
{
tempCanvas.DrawPath(iconPath, _outlinePaint);
Expand All @@ -214,10 +215,25 @@ private SKImage GenerateSvgIcon(string iconSvgString, SKColor iconColor)
var newSize = (int)(_fontSize / 0.6); // 20*20px @ 12pt font
var imageInfo = new SKImageInfo(newSize, newSize);
var resizedBitmap = tempBitmap.Resize(imageInfo, SKFilterQuality.High);

resizedBitmap.SetImmutable();
return SKImage.FromBitmap(resizedBitmap);
}

private SKPaint GetSvgIconPaint(SKColor iconColor)
{
ref var iconPaint = ref CollectionsMarshal.GetValueRefOrAddDefault(_iconPaints, iconColor, out var exists);

if (!exists)
{
iconPaint = new SKPaint();
iconPaint.Color = iconColor;
iconPaint.IsAntialias = true;
}

return iconPaint;
}

/// <summary>
/// Splits a comment into 2 comments based on the start index of a custom re-sub message
/// </summary>
Expand Down Expand Up @@ -338,6 +354,10 @@ private void Dispose(bool isDisposing)
_giftAnonymousIcon?.Dispose();
_bitBadgeTierNotificationIcon?.Dispose();
_outlinePaint?.Dispose();
foreach (var (_, paint) in _iconPaints)
{
paint.Dispose();
}
}
}
finally
Expand Down

0 comments on commit 33b6dad

Please sign in to comment.