最近在做c#跨平台項目的時候,遇到了avalonia項目在銀河麒麟操作系統上運行時報錯:default font family is not be null or empty。但是在windows、ubuntu上運行沒有問題。最終通過查看avalonia源碼和官方提供的測試示例找到解決方案。(記錄一下,避免以后忘了。。。)
第一步:將字體最為項目的嵌入資源導入進項目。
<ItemGroup> <EmbeddedResource Include="Assets\Fonts\msyh.ttc" /> <EmbeddedResource Include="Assets\Fonts\msyhbd.ttc" /> <EmbeddedResource Include="Assets\Fonts\msyhl.ttc" /> </ItemGroup>
第二步:新建一個類,作為自定義字體管理類。
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()函數,將我們自定義的字體管理對象注冊進去。
/// <summary> /// override RegisterServices register custom service /// </summary> public override void RegisterServices() { AvaloniaLocator.CurrentMutable.Bind<IFontManagerImpl>().ToConstant(new CustomFontManagerImpl()); base.RegisterServices(); }
經過以上三個步驟,我的程序可以在windows、Ubuntu、銀河麒麟操作系統上正常運行,沒有出錯。