CustomFontManagerImpl.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System.Collections.Generic;
  2. using System.Globalization;
  3. using System.Linq;
  4. using Avalonia.Media;
  5. using Avalonia.Media.Fonts;
  6. using Avalonia.Platform;
  7. using SkiaSharp;
  8. namespace Avalonia.Skia.UnitTests
  9. {
  10. public class CustomFontManagerImpl : IFontManagerImpl
  11. {
  12. private readonly Typeface[] _customTypefaces;
  13. private readonly Typeface _defaultTypeface =
  14. new Typeface("resm:Avalonia.Skia.UnitTests.Assets?assembly=Avalonia.Skia.UnitTests#Noto Mono");
  15. private readonly Typeface _emojiTypeface =
  16. new Typeface("resm:Avalonia.Skia.UnitTests.Assets?assembly=Avalonia.Skia.UnitTests#Twitter Color Emoji");
  17. public CustomFontManagerImpl()
  18. {
  19. _customTypefaces = new[] { _emojiTypeface, _defaultTypeface };
  20. }
  21. public string GetDefaultFontFamilyName()
  22. {
  23. return _defaultTypeface.FontFamily.ToString();
  24. }
  25. public IEnumerable<string> GetInstalledFontFamilyNames(bool checkForUpdates = false)
  26. {
  27. return _customTypefaces.Select(x => x.FontFamily.Name);
  28. }
  29. public bool TryMatchCharacter(int codepoint, FontWeight fontWeight, FontStyle fontStyle, FontFamily fontFamily,
  30. CultureInfo culture, out FontKey fontKey)
  31. {
  32. foreach (var customTypeface in _customTypefaces)
  33. {
  34. if (customTypeface.GlyphTypeface.GetGlyph((uint)codepoint) == 0)
  35. continue;
  36. fontKey = new FontKey(customTypeface.FontFamily, fontWeight, fontStyle);
  37. return true;
  38. }
  39. var fallback = SKFontManager.Default.MatchCharacter(codepoint);
  40. fontKey = new FontKey(fallback?.FamilyName ?? SKTypeface.Default.FamilyName, fontWeight, fontStyle);
  41. return true;
  42. }
  43. public IGlyphTypefaceImpl CreateGlyphTypeface(Typeface typeface)
  44. {
  45. switch (typeface.FontFamily.Name)
  46. {
  47. case "Twitter Color Emoji":
  48. case "Noto Mono":
  49. var typefaceCollection = SKTypefaceCollectionCache.GetOrAddTypefaceCollection(typeface.FontFamily);
  50. var skTypeface = typefaceCollection.Get(typeface);
  51. return new GlyphTypefaceImpl(skTypeface);
  52. default:
  53. return new GlyphTypefaceImpl(SKTypeface.FromFamilyName(typeface.FontFamily.Name,
  54. (SKFontStyleWeight)typeface.Weight, SKFontStyleWidth.Normal, (SKFontStyleSlant)typeface.Style));
  55. }
  56. }
  57. }
  58. }