2010-03-28 101 views
0

我刚刚添加了一个ttf文件作为“文件”项目(C#2008 express)并为嵌入式资源构建选项。嵌入式ttf作为嵌入式资源:无法引用它

试图建立这种字体类似这样的,当我有问题: (我知道下一行是错误的...)

this.label1.Font = AlarmWatch.Properties.Resources.Baby_Universe; 

错误1无法隐式转换类型 “字节[ ]”到 'System.Drawing.Font' C:\用户\本乡\文档\ Visual Studio中 \项目\ AlarmWatch \ AlarmWatch \ Form1.Designer.cs 57 32 AlarmWatch

我知道它是字节[]因为我已经设置的选项构建嵌入式资源,但此行是正确的比较:

this.label1.Font = new System.Drawing.Font("OCR A Extended", 
          24F, System.Drawing.FontStyle.Regular, 
          System.Drawing.GraphicsUnit.Point, ((byte)(0))); 

如何设置this.label1使用新字体?

回答

2

在命名空间中有一个AddMemoryFont方法,它从内存中加载字体(它需要一个指向内存块的指针,因此您需要执行一些不安全的操作来获取指向您的字节数组的指针 - I发现example here)。更多关于method on MSDN

还有一个相关的StackOverflow question显示如何导入Win API函数直接加载字体(以防上述.NET方法不起作用)。

编辑的关键部件从Visual Basic的翻译可能是这样的(还没有检查它虽然):

// This should be probably a field of some class 
PrivateFontCollection pfc = new PrivateFontCollection(); 

// allocate memory and copy byte[] to the location 
IntPtr data = Marshal.AllocCoTaskMem(yourByteArray.Length); 
Marshal.Copy(yourFontArray, 0, data, yourFontArray.Length); 

// pass the font to the font collection 
pfc.AddMemoryFont(data, fontStream.Length) 

// Free the unsafe memory 
Marshal.FreeCoTaskMem(data) 

一旦你有了这个,你应该能够引用的字体使用其通常的名称。

+0

嗨,谢谢你的回答。我去了那个页面,但是,我不知道该如何将代码放在我的应用程序中,因为它是基于视觉的,并且不能很好地翻译它... – HoNgOuRu 2010-03-28 23:38:57

+0

如何将帖子设置为回复或接受或其他? – HoNgOuRu 2010-03-28 23:58:33

+0

谢谢,我现在就这样做! – HoNgOuRu 2010-03-29 01:48:27

0
private static void AddFontFromResource(PrivateFontCollection privateFontCollection, string fontResourceName) 
{ 
    var fontBytes = GetFontResourceBytes(typeof (App).Assembly, fontResourceName); 
    var fontData = Marshal.AllocCoTaskMem(fontBytes.Length); 
    Marshal.Copy(fontBytes, 0, fontData, fontBytes.Length); 
    privateFontCollection.AddMemoryFont(fontData, fontBytes.Length); 
    Marshal.FreeCoTaskMem(fontData); 
} 

private static byte[] GetFontResourceBytes(Assembly assembly, string fontResourceName) 
{ 
    var resourceStream = assembly.GetManifestResourceStream(fontResourceName); 
    if (resourceStream == null) 
     throw new Exception(string.Format("Unable to find font '{0}' in embedded resources.", fontResourceName)); 
    var fontBytes = new byte[resourceStream.Length]; 
    resourceStream.Read(fontBytes, 0, (int)resourceStream.Length); 
    resourceStream.Close(); 
    return fontBytes; 
}