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

  • 相关阅读:
    LInux常用命令:总结
    SpringBoot声明式事务(转)
    连接linux客户端工具
    查看servlet 3.0文档方法
    通过spring.io找spring历史版本
    归并排序(比希尔还要快)
    快速排序(比希尔排序还要快)
    希尔排序(交换式和移位式)
    插入排序
    选择排序(时间复杂度O(n^2))
  • 原文地址:https://www.cnblogs.com/lindexi/p/12086429.html
Copyright © 2011-2022 走看看