C#WPF如何从字节数组加载FontFamily? [英] C# WPF How to load a FontFamily from a byte array?
问题描述
好吧,我基本上想从字面上嵌入我将在WPF应用程序中使用的字体集合.它们存储在我自己的虚拟文件系统(如WinRAR)中,我只想通过字节数组或内存流来加载它们.但是,我找不到任何可行的解决方案.我尝试了PrivateFontCollection,但最后,我意识到Families属性适用于WinForms(System.Drawing.FontFamily和 NOT System.Windows.Media.FontFamily).我还对将它们提取到操作系统级别进行了分类.
Well, I basically want to literally embed my collection of fonts that I will be using in my WPF app. They're stored in my own virtual file system (like WinRAR), and I just want to load them through a byte array or a memory stream. However, I haven't been able to find any working solutions. I've tried PrivateFontCollection, but at the end, I realized that the Families property is for WinForms (System.Drawing.FontFamily and NOT System.Windows.Media.FontFamily). I also classify extracting them to the OS level out of the question.
所以问题仍然存在:
如何使用字节数组或内存流加载System.Windows.Media.FontFamily?
How to load a System.Windows.Media.FontFamily using a byte array or a memory stream?
这是一个.ttf文件(True Type字体)
This is a .ttf file (True Type Font)
推荐答案
您已发布此解决方案:
如果有人正在寻找这种解决方案,那就在这里:
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!