2015-11-17 60 views
0

我在應用程序的資源中有一個字節數組。這是一種自定義字體樣式。 我想將此字節數組轉換爲System.Windows.Media.FontFamily使用C#將字節[]轉換爲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

你能幫我嗎?

+0

這是不正確的代碼,只要字體可以使用,您傳遞的指針必須保持有效。它不會,垃圾收集器在堆積時會將其分解。谷歌「addmemoryfont marshal.alloccotaskmem」,避免*很多馬車示例,馬上致電Marshal.FreeCoTaskMem()。 –

+1

爲什麼不直接在應用程序中打包'Font'?在這裏閱讀:https://msdn.microsoft.com/library/ms753303(v=vs.100).aspx – Jasper

+0

隨着你給我的網站,我不能讓那個賈斯珀你能幫我嗎? – Moussawi

回答

0

有類似的需求,這裏是我的方法(假設你不知道字體名稱和字體沒有嵌入)。 如果有人有更好的主意,請不要猶豫,添加一些意見,請!

 //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); 
+0

我找到了解決我的問題的方法。我向你展示了我的想法。你把你的字體放到項目資源中。所以創建一個字節數組。之後,你可以像這樣創建一個'FontFamily':'FontFamily fontFamily = new FontFamily(new Uri(「pack:// application:,,, /」),「./#Your font Name」);'I'll希望這可以幫助你;-) – Moussawi