最近在作c#跨平臺項目的時候,遇到了avalonia項目在銀河麒麟操做系統上運行時報錯:default font family is not be null or empty。可是在windows、ubuntu上運行沒有問題。最終經過查看avalonia源碼和官方提供的測試示例找到解決方案。(記錄一下,避免之後忘了。。。)ubuntu
第一步:將字體最爲項目的嵌入資源導入進項目。c#
<ItemGroup> <EmbeddedResource Include="Assets\Fonts\msyh.ttc" /> <EmbeddedResource Include="Assets\Fonts\msyhbd.ttc" /> <EmbeddedResource Include="Assets\Fonts\msyhl.ttc" /> </ItemGroup>
第二步:新建一個類,做爲自定義字體管理類。windows
public class CustomFontManagerImpl : IFontManagerImpl { private readonly Typeface[] _customTypefaces; private readonly string _defaultFamilyName; //Load font resources in the project, you can load multiple font resources private readonly Typeface _defaultTypeface = new Typeface("resm:AvaloniaApplication1.Assets.Fonts.msyh#微軟雅黑"); public CustomFontManagerImpl() { _customTypefaces = new[] { _defaultTypeface }; _defaultFamilyName = _defaultTypeface.FontFamily.FamilyNames.PrimaryFamilyName; } public string GetDefaultFontFamilyName() { return _defaultFamilyName; } public IEnumerable<string> GetInstalledFontFamilyNames(bool checkForUpdates = false) { return _customTypefaces.Select(x => x.FontFamily.Name); } private readonly string[] _bcp47 = { CultureInfo.CurrentCulture.ThreeLetterISOLanguageName, CultureInfo.CurrentCulture.TwoLetterISOLanguageName }; public bool TryMatchCharacter(int codepoint, FontStyle fontStyle, FontWeight fontWeight, FontFamily fontFamily, CultureInfo culture, out Typeface typeface) { foreach (var customTypeface in _customTypefaces) { if (customTypeface.GlyphTypeface.GetGlyph((uint)codepoint) == 0) { continue; } typeface = new Typeface(customTypeface.FontFamily.Name, fontStyle, fontWeight); return true; } var fallback = SKFontManager.Default.MatchCharacter(fontFamily?.Name, (SKFontStyleWeight)fontWeight, SKFontStyleWidth.Normal, (SKFontStyleSlant)fontStyle, _bcp47, codepoint); typeface = new Typeface(fallback?.FamilyName ?? _defaultFamilyName, fontStyle, fontWeight); return true; } public IGlyphTypefaceImpl CreateGlyphTypeface(Typeface typeface) { SKTypeface skTypeface; switch (typeface.FontFamily.Name) { case FontFamily.DefaultFontFamilyName: case "微軟雅黑": //font family name skTypeface = SKTypeface.FromFamilyName(_defaultTypeface.FontFamily.Name); break; default: skTypeface = SKTypeface.FromFamilyName(typeface.FontFamily.Name, (SKFontStyleWeight)typeface.Weight, SKFontStyleWidth.Normal, (SKFontStyleSlant)typeface.Style); break; } return new GlyphTypefaceImpl(skTypeface); } }
第三步:在App.axaml.cs中重寫RegisterServices()函數,將咱們自定義的字體管理對象註冊進去。ide
/// <summary> /// override RegisterServices register custom service /// </summary> public override void RegisterServices() { AvaloniaLocator.CurrentMutable.Bind<IFontManagerImpl>().ToConstant(new CustomFontManagerImpl()); base.RegisterServices(); }
通過以上三個步驟,個人程序能夠在windows、Ubuntu、銀河麒麟操做系統上正常運行,沒有出錯。函數