title

author

date

CreateTime

categories

WPF 从文件加载字体

lindexi

2019-08-02 17:10:33 +0800

2018-2-13 17:23:3 +0800

WPF

本文告诉大家从文件加载字体。在wpf 使用 fontfamily 显示指定的 ttf 显示字体。

假如有字体在 ​​C:\Projects\MyProj\free3of9.ttf​​ ,可以使用 PrivateFontCollection 添加字体。

下面的代码就可以使用本地的 free3of9.ttf ,需要注意添加的 FontFamily 是需要知道字体名,和传入 PrivateFontCollection 才可以使用。

using System.Drawing;

PrivateFontCollection collection = new PrivateFontCollection();
collection.AddFontFile(@"C:\Projects\MyProj\free3of9.ttf");
FontFamily fontFamily = new FontFamily("Free 3 of 9", collection);
Font font = new Font(fontFamily, height);


另一个方法是去掉字体的后缀名,直接写在 FontFamily ,我比较希望使用下面的方法

FontFamily fontFamily = new FontFamily(@"C:\Projects\MyProj\#free3of9");


在 WPF 里面 FontFamily 存在与 System.Drawing 和 System.Windows.Media 命名空间下,同时两个命名空间的字体是不能互换的。以上方法使用的是 System.Drawing 命名空间的字体

对 System.Windows.Media 命名空间的 FontFamily 需要使用以下两个方法之一拿到本地字体

第一个方法是通过 URI 加上字体名

var file = @"C:\lindexi\xx.ttf";
var uri = new Uri(file);
FontFamily fontFamily = new FontFamily(uri, "字体名");


可以通过双击字体看到字体名,或通过下面的第二个方法拿到字体名同时使用本地字体

var fontFile = @"C:\lindexi\xx.ttf";

var glyphTypeface = new GlyphTypeface(new Uri(fontFile));

// 获取字体名
var fontName = glyphTypeface.FamilyNames.Values.FirstOrDefault();
var directory = Path.GetDirectoryName(fontFile);
var fontUri = $"{new Uri(directory).AbsoluteUri}/#{fontName}";
var fontFamily = new FontFamily(fontUri);