如何在WPF(C#)中批量加载字体图标
前言
在使用ttf格式字体图标文件时,有可能会遇到要列举出文件中所有图标的情况。如下
获取ttf文件中所有的UniCode
代码如下(示例):
public static IEnumerable<int> GetUniCodes(string uri)
{
var result = new List<int>();
var families = Fonts.GetFontFamilies(uri);
foreach (var fontFamily in families)
{
var typeface = fontFamily.GetTypefaces().FirstOrDefault();
if (!(typeface?.TryGetGlyphTypeface(out var glyph) ?? false)) continue;
var characterMap = glyph.CharacterToGlyphMap;
foreach (var (key, _) in characterMap) result.Add(key);
}
return result;
}
写入WPF界面
代码如下(示例):
public void LoadFonts()
{
ShowFonts.Clear();
if (Path.GetExtension(FontUri).ToLower() != ".ttf")
{
MessageBox.Show("选择的不是字体文件");
return;
}
var familyName = new GlyphTypeface(new Uri(FontUri)).FamilyNames.FirstOrDefault().Value;
IconFontFamily =
$"{Path.GetDirectoryName(FontUri)?.Replace("\\", "/")}/#{familyName}";
GetUniCodes(FontUri).Select(point => new FontModel()
{
fontUri = char.ConvertFromUtf32(point),
title = $"&#x{Convert.ToInt64(point):x};"
}).ToList().ForEach(r=>ShowFonts.Add(r));
}