表格字体嵌入

时间:2015-04-08 07:08:39

标签: c# winforms fonts

我试图弄清楚这段代码中发生的事情已经有一段时间了。

[System.Runtime.InteropServices.DllImport("gdi32.dll")]
private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, 
    uint cbFont, IntPtr pdv, [System.Runtime.InteropServices.In] ref uint pcFonts);

public static PrivateFontCollection myFontCollection = new PrivateFontCollection();
public static FontFamily RobotoBold = null;
public static FontFamily RobotoThin = null;

public enum Fonts
{
    Roboto_Bold = 0,
    Roboto_Thin = 1
}

public static void loadFonts()
{
   Array fonts = Enum.GetValues(typeof(Fonts));

   foreach (Fonts font in fonts)
   {
       byte[] fontData = (byte[])Resources.ResourceManager.GetObject(font.ToString());
       IntPtr fontPtr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(fontData.Length);
       System.Runtime.InteropServices.Marshal.Copy(fontData, 0, fontPtr, fontData.Length);
       uint dummy = 0;
       myFontCollection.AddMemoryFont(fontPtr, fontData.Length);
       AddFontMemResourceEx(fontPtr, (uint)fontData.Length, IntPtr.Zero, ref dummy);
       System.Runtime.InteropServices.Marshal.FreeCoTaskMem(fontPtr);
   }

   RobotoBold = Program.myFontCollection.Families[(int)Program.Fonts.Roboto_Bold];
   RobotoThin = Program.myFontCollection.Families[(int)Program.Fonts.Roboto_Thin];
}

实际上它读取了我作为资源嵌入的.ttf,但如果我调试,在FontFamilys中我读到了这条消息:

{Name = The name 'name' does not exist in the current context}

我已经试图弄清楚发生了什么,但无法找到我的错误。 使用ResourceManager正确读取资源,但我认为添加字体时出现了问题。

0 个答案:

没有答案