1.在项目中附带一个默认字体,如下图:
2.创建一个自定义字体管理类实现IFontManagerImpl接口:
public class CustomFontManagerImpl : IFontManagerImpl
{
#region 私有成员
private readonly MyFont[] _fonts = new MyFont[] {
new MyFont() {
FontName = "Source Han Sans CN",
Path = "avares://项目名/Assets/Fonts/SourceHanSansCN-Regular.ttf",
Typeface = new Typeface(new FontFamily(new Uri("avares://项目名/Assets/Fonts/SourceHanSansCN-Regular.ttf"), "Source Han Sans CN")),
FontWeight = FontWeight.Normal
},
new MyFont() {
FontName = "Source Han Sans CN",
Path = "avares://项目名/Assets/Fonts/SourceHanSansCN-Bold.ttf",
Typeface = new Typeface(new FontFamily(new Uri("avares://项目名/Assets/Fonts/SourceHanSansCN-Bold.ttf"), "Source Han Sans CN")),
FontWeight = FontWeight.Bold
}
};
#endregion
#region 实现接口
public IGlyphTypefaceImpl CreateGlyphTypeface(Typeface typeface)
{
var font = Array.Find(_fonts, _ => _.FontName == typeface.FontFamily?.Name);
if (font == null)
font = _fonts.FirstOrDefault(_ => _.FontWeight == typeface.Weight) ?? _fonts.FirstOrDefault();
if (font.SKTypeface == null)
{
var assets = (IAssetLoader)AvaloniaLocator.Current.GetService(typeof(IAssetLoader));
font.SKTypeface = SKTypeface.FromStream(assets.Open(new Uri(font?.Path)));
}
return new GlyphTypefaceImpl(font.SKTypeface);
}
public string GetDefaultFontFamilyName()
{
return _fonts.FirstOrDefault()?.FontName;
}
public IEnumerable<string> GetInstalledFontFamilyNames(bool checkForUpdates = false)
{
return _fonts.Select(_ => _.FontName);
}
public bool TryMatchCharacter(int codepoint, FontStyle fontStyle, FontWeight fontWeight, FontFamily fontFamily, CultureInfo culture, out Typeface typeface)
{
var font = Array.Find(_fonts, _ => _.Typeface.GlyphTypeface.GetGlyph((uint)codepoint) == 0);
if (font == null)
font = _fonts.FirstOrDefault();
typeface = new Typeface(font.Typeface.FontFamily.Name, fontStyle, fontWeight);
return true;
}
#endregion
#region 私有类
private class MyFont
{
internal string FontName { get; set; }
internal string Path { get; set; }
internal Typeface Typeface { get; set; }
internal SKTypeface SKTypeface { get; set; }
internal FontWeight FontWeight { get; set; }
}
#endregion
}
3.重写App类的RegisterServices方法
public partial class App : PrismApplication
{
public override void RegisterServices()
{
AvaloniaLocator.CurrentMutable.Bind<IFontManagerImpl>().ToConstant(new CustomFontManagerImpl());
base.RegisterServices();
}
}
4.如果需要支持其它类型的字体,如相同字体的粗体,就可以在 _fonts中补充相应的字体,如下图:
同时,在接口的实现方法CreateGlyphTypeface中进行相关处理即可