使用C#将byte []转换为System.Windows.Media.FontFamily

时间:2015-11-17 13:02:40

标签: c# wpf xaml

我有一个字节数组到应用程序的资源中。这是一种自定义字体样式。 我想将此字节数组转换为System.Windows.Media.FontFamily

我的代码:

byte[] fontdata = Application_IAD.Properties.Resources.Sansation_Regular;

unsafe
{
     fixed (byte* pFontData = fontdata)
     {
         pfc.AddMemoryFont((System.IntPtr)pFontData, fontdata.Length);
     }
}

使用此代码,我有一个Sytem.Drawing.FontFamily,但我无法将其转换为System.Windows.Media.FontFamily

你能帮帮我吗?

1 个答案:

答案 0 :(得分:1)

有类似的需求,这是我的方法(假设您不知道字体系列名称和字体未嵌入)。 如果有人有更好的想法,请随时添加一些评论!

        //Writing bytes to a temporary file.
        string tempFontFileLoation = "testFont.ttf";
        File.WriteAllBytes(tempFontFileLoation, yourBytesHere);

        //Creating an instance of System.Windows.Media.GlyphTypeface.
        //From here we will read all the needed font details.
        var glyphTypeface = new GlyphTypeface(new Uri(tempFontFileLoation));

        //Reading font family name
        string fontFamilyName = String.Join(" ", glyphTypeface.FamilyNames.Values.ToArray<string>());

        //This is what we actually need... the right font family name, to be able to create a correct FontFamily Uri
        string fontUri = new Uri(tempFontFileLoation.Replace(Path.GetFileName(tempFontFileLoation), ""), UriKind.RelativeOrAbsolute).AbsoluteUri + "/#" + fontFamilyName;

        //And here is the instance of System.Windows.Media.FontFamily
        var fontFamily = new FontFamily(fontUri);