C# WPF How to load a FontFamily from a byte array?

Viewed 1602

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.

So the question still remains:

How to load a System.Windows.Media.FontFamily using a byte array or a memory stream?

EDIT:

This is a .ttf file (True Type Font)

1 Answers

You have posted this solution:

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);
}
Related