编程技术 · 2018 年 12 月 25 日 0

C# 引用外部字体文件

                //从外部文件加载字体文件  
                PrivateFontCollection font = new PrivateFontCollection();
                font.AddFontFile(Environment.CurrentDirectory + @"\BITSUMISHI.TTF");
                //检测字体类型是否可用
                var r = font.Families[0].IsStyleAvailable(FontStyle.Regular);
                var b = font.Families[0].IsStyleAvailable(FontStyle.Bold);
                //定义成新的字体对象
                FontFamily myFontFamily = new FontFamily(font.Families[0].Name, font);
                Font myFont = new Font(myFontFamily, 22, FontStyle.Bold);
                //将字体显示到控件  
                label1.Font = myFont;
public Font GetResoruceFont(byte[] bytes)
{
    System.Drawing.Text.PrivateFontCollection pfc = new System.Drawing.Text.PrivateFontCollection();
    IntPtr MeAdd = Marshal.AllocHGlobal(bytes.Length);
    Marshal.Copy(bytes, 0, MeAdd, bytes.Length);
    pfc.AddMemoryFont(MeAdd, bytes.Length);
    return new Font(pfc.Families[0], 15, FontStyle.Regular);
}

使用自定义字体:

PrivateFontCollection prc = new PrivateFontCollection();
prc.AddFontFile(“自定义字体路径”);
Font f = new Font(prc.Families[0], 12);

使用本地字体:

InstalledFontCollection fc = new InstalledFontCollection();
Font a = fc.Families.Where(d => d.Name.Contains(“要使用的本地字体名称”)).FirstOrDefault();