zoukankan      html  css  js  c++  java
  • 2019-8-2-WPF-从文件加载字体

    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:ProjectsMyProjfree3of9.ttf ,可以使用 PrivateFontCollection 添加字体。

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

    using System.Drawing;
    
    PrivateFontCollection collection = new PrivateFontCollection();
    collection.AddFontFile(@"C:ProjectsMyProjfree3of9.ttf");
    FontFamily fontFamily = new FontFamily("Free 3 of 9", collection);
    Font font = new Font(fontFamily, height);

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

    FontFamily fontFamily = new FontFamily(@"C:ProjectsMyProj#free3of9");

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

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

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

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

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

                var fontFile = @"C:lindexixx.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);

    https://stackoverflow.com/a/24022783/6116637

  • 相关阅读:
    八皇后之回溯算法
    手撕堆排序 优先级队列的实现方式
    扩展1000!(n!)的尾数零的个数
    #12. 整数转罗马数字 穷举法
    #11 盛最多水的容器
    Sql Server 复制数据库
    常见dos命令行
    JSP页面中,EL表达式获取根路径。
    maven springTest结合junit单元测试
    【Java异常】Exception in thread“main” java util ConcurrentModificationException的解决方案
  • 原文地址:https://www.cnblogs.com/lindexi/p/12086429.html
Copyright © 2011-2022 走看看