我在我的资源中嵌入了一个.ttf字体文件(“Amatic Bold”,具体而言),我使用下面的代码获取字体。 我试过代码FOM这个帖子:How do I Embed a font with my C# application? (using Visual Studio 2005)C#中嵌入的资源字体无法正常工作
这是我实现:
static public Font GetCustomFont (byte[] fontData, float size, FontStyle style)
{
if (_fontCollection == null) _fontCollection = new PrivateFontCollection();
IntPtr fontPtr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(fontData.Length);
System.Runtime.InteropServices.Marshal.Copy(fontData, 0, fontPtr, fontData.Length);
_fontCollection.AddMemoryFont(fontPtr, fontData.Length);
System.Runtime.InteropServices.Marshal.FreeCoTaskMem(fontPtr);
return new Font(_fontCollection.Families[0], size, style);
}
进出口使用它这样:
Font font = GetCustomFont(Properties.MainResources.Amatic_Bold, 25, System.Drawing.FontStyle.Bold);
问题是字体正在加载但使用时不能正确显示;它看起来像是一个“Arial”或其他标准字体,而不是它应该是的。 如果我在Windows中安装的字体,它的工作原理(我想是显而易见的......)
我搜索了现有的答案,但could'nt找到我确切的问题...
任何帮助将不胜感激。 在此先感谢。
这个可怕的bug代码就像病毒一样,它非常难以摆脱。您正在被字体保存,它是一种OpenType字体。仅适用于WPF或Direct2D应用程序。字体映射器找到可以在Winforms应用程序中工作的替代品。 –
谢谢,@HansPassant。使用字体而不必安装它有什么好的选择吗? –
当您安装字体时它实际上工作吗?然后修复此代码中的错误。您不能调用Marshal.FreeCoTaskMem(),直到不再使用字体并调用._fontCollection.Dispose()方法为止_fontCollection.Families [0]总是返回第一个字体,而不是最后一个加载的字体。 –