C# WPF 如何从字节数组加载 FontFamily?

标签 c# arrays wpf fonts stream

好吧,我基本上想直接嵌入我将在我的 WPF 应用程序中使用的字体集合。它们存储在我自己的虚拟文件系统(如 WinRAR)中,我只想通过字节数组或内存流加载它们。但是,我一直无法找到任何可行的解决方案。我试过 PrivateFontCollection,但最后,我意识到 Families 属性适用于 WinForms(System.Drawing.FontFamily 和 NOT System.Windows.Media.FontFamily)。我也将它们分类到操作系统级别,这是不可能的。

所以问题依然存在:

如何使用字节数组或内存流加载 System.Windows.Media.FontFamily?

编辑:

这是一个 .ttf 文件(True Type 字体)

最佳答案

您已发布此解决方案:

If someone is searching for this kind of solution, it's right here:

public static void Load(MemoryStream stream)
{
    byte[] streamData = new byte[stream.Length];
    stream.Read(streamData, 0, streamData.Length);
    IntPtr data = Marshal.AllocCoTaskMem(streamData.Length); // Very important.
    Marshal.Copy(streamData, 0, data, streamData.Length);
    PrivateFontCollection pfc = new PrivateFontCollection();
    pfc.AddMemoryFont(data, streamData.Length);
    MemoryFonts.Add(pfc); // Your own collection of fonts here.
    Marshal.FreeCoTaskMem(data); // Very important.
}

public static System.Windows.Media.FontFamily LoadFont(int fontId)
{
    if (!Exists(fontId))
    {
        return null;
    }
    /*
    NOTE:
    This is basically how you convert a System.Drawing.FontFamily to System.Windows.Media.FontFamily, using PrivateFontCollection.
    */
    return new System.Windows.Media.FontFamily(MemoryFonts[fontId].Families[0].Name);
}

关于C# WPF 如何从字节数组加载 FontFamily?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44912480/

相关文章:

c# - DevExpress:通过代码设置数据源和列标题

c# - 有没有什么方法可以安全地进行图像量化并且无需编码?

javascript搜索数组,返回找到的键

javascript - Array 构造函数的合法使用

C#:HttpClient,服务器违反了协议(protocol)。部分=响应状态行

c# - DataGrid wpf MVVM 内的按钮

c# - Linq 每次迭代选择 5 个项目

c# - Shannon-fano 编码算法 - 较大集合上的奇怪行为

c++ - 用户定义的数组大小

c# - 如何绑定(bind)网格行高?