mirror of https://github.com/ErsatzTV/ErsatzTV.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.5 KiB
48 lines
1.5 KiB
using Microsoft.Extensions.Logging; |
|
using SkiaSharp; |
|
using Topten.RichTextKit; |
|
|
|
namespace ErsatzTV.Infrastructure.Streaming.Graphics.Fonts; |
|
|
|
public sealed class CustomFontMapper(ILogger<CustomFontMapper> logger) : FontMapper |
|
{ |
|
private readonly Dictionary<string, List<SKTypeface>> _customFonts = new(); |
|
|
|
public void LoadPrivateFont(Stream stream, string familyName) |
|
{ |
|
var typeface = SKTypeface.FromStream(stream) ?? |
|
throw new ArgumentException("Cannot load font from stream", nameof(stream)); |
|
var qualifiedName = familyName ?? typeface.FamilyName; |
|
|
|
if (typeface.FontSlant != SKFontStyleSlant.Upright) |
|
{ |
|
qualifiedName += "-Italic"; |
|
} |
|
|
|
if (!_customFonts.TryGetValue(qualifiedName, out var listFonts)) |
|
{ |
|
listFonts = []; |
|
_customFonts[qualifiedName] = listFonts; |
|
} |
|
|
|
listFonts.Add(typeface); |
|
} |
|
|
|
public override SKTypeface TypefaceFromStyle(IStyle style, bool ignoreFontVariants) |
|
{ |
|
var qualifiedName = style.FontFamily; |
|
if (style.FontItalic) |
|
{ |
|
qualifiedName += "-Italic"; |
|
} |
|
|
|
if (_customFonts.TryGetValue(qualifiedName, out List<SKTypeface> listFonts) && listFonts.Count != 0) |
|
{ |
|
return listFonts.MinBy(font => Math.Abs(font.FontWeight - style.FontWeight))!; |
|
} |
|
|
|
logger.LogWarning("Could not find font {Name}; using default", qualifiedName); |
|
|
|
return base.TypefaceFromStyle(style, ignoreFontVariants); |
|
} |
|
} |