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 Avalonia.Skia;
8 using SkiaSharp;
9
10 namespace AvaloniaDemo
11 {
12 public class CustomFontManagerImpl : IFontManagerImpl
13 {
14 private readonly Typeface[] _customTypefaces;
15 private readonly string _defaultFamilyName;
16
17 //Load font resources in the project, you can load multiple font resources
18 private readonly Typeface _defaultTypeface =
19 new Typeface("resm:AvaloniaDemo.Assets.Fonts.msyh#微软雅黑");
20
21 public CustomFontManagerImpl()
22 {
23 _customTypefaces = new[] { _defaultTypeface };
24 _defaultFamilyName = _defaultTypeface.FontFamily.FamilyNames.PrimaryFamilyName;
25 }
26
27 public string GetDefaultFontFamilyName()
28 {
29 return _defaultFamilyName;
30 }
31
32 public IEnumerable<string> GetInstalledFontFamilyNames(bool checkForUpdates = false)
33 {
34 return _customTypefaces.Select(x => x.FontFamily.Name);
35 }
36
37 private readonly string[] _bcp47 = { CultureInfo.CurrentCulture.ThreeLetterISOLanguageName, CultureInfo.CurrentCulture.TwoLetterISOLanguageName };
38
39 public bool TryMatchCharacter(int codepoint, FontStyle fontStyle, FontWeight fontWeight, FontFamily fontFamily,
40 CultureInfo culture, out Typeface typeface)
41 {
42 foreach (var customTypeface in _customTypefaces)
43 {
44 if (customTypeface.GlyphTypeface.GetGlyph((uint)codepoint) == 0)
45 {
46 continue;
47 }
48
49 typeface = new Typeface(customTypeface.FontFamily.Name, fontStyle, fontWeight);
50
51 return true;
52 }
53
54 var fallback = SKFontManager.Default.MatchCharacter(fontFamily?.Name, (SKFontStyleWeight)fontWeight,
55 SKFontStyleWidth.Normal, (SKFontStyleSlant)fontStyle, _bcp47, codepoint);
56
57 typeface = new Typeface(fallback?.FamilyName ?? _defaultFamilyName, fontStyle, fontWeight);
58
59 return true;
60 }
61
62 public IGlyphTypefaceImpl CreateGlyphTypeface(Typeface typeface)
63 {
64 SKTypeface skTypeface;
65
66 switch (typeface.FontFamily.Name)
67 {
68 case FontFamily.DefaultFontFamilyName:
69 case "微软雅黑": //font family name
70 skTypeface = SKTypeface.FromFamilyName(_defaultTypeface.FontFamily.Name); break;
71 default:
72 skTypeface = SKTypeface.FromFamilyName(typeface.FontFamily.Name,
73 (SKFontStyleWeight)typeface.Weight, SKFontStyleWidth.Normal, (SKFontStyleSlant)typeface.Style);
74 break;
75 }
76
77
78 //解决linux系统下skTypeface是null
79 if (skTypeface == null)
80 {
81 skTypeface = SKTypeface.FromFamilyName(_defaultTypeface.FontFamily.Name);
82 }
83
84 //如果是centos7之类的使用linux里面的字体
85 if (skTypeface == null)
86 {
87 skTypeface = SKTypeface.FromFamilyName("WenQuanYi Micro Hei");
88 }
89
90 return new GlyphTypefaceImpl(skTypeface);
91 }
92
93 }
94 }
PS:重点参考标红部分