我已经下载了一个字体[Betsy Flanagan] [1],我希望在我的程序中使用它来显示屏幕键盘快捷键及其在各种程序中的含义。
但是,在Visual Studio 2010中为标签选择字体时,出现错误消息“仅支持TrueType字体。这不是TrueType字体。”
我有什么方法可以在.NET程序中显示带有此字体的文本?因为这是一个专门的toast-like形式,只有一个标签需要有这个特定的字体,我真的不在乎它是否是一个黑客(如P / Invoke或类似的。)
注意:这是.NET 4.0 Winforms应用程序。
答案 0 :(得分:2)
如果this is the font you're trying to use,那么您的本地实例可能已损坏?
当我尝试将标签和其他winforms控件设置为Betsy时,VS2010表现良好。下载我链接的那个,看看是否有效。我的看法是,如果您安装了有效的TTF,VS将不会例外。
答案 1 :(得分:1)
查看此代码,该代码将嵌入字体作为资源加载并在适用的控件中使用,该示例显示嵌入OCR字体的用法
private PrivateFontCollection pfc = new PrivateFontCollection();
private Font _fntOCRFont = null;
private enum FontEnum{
OCR = 0
};
private FontSize _fntSizeDefault = FontSize.Small;
private float _fFontSize = 0.0F;
private void InitOCRFont(){
try{
System.IO.Stream streamFont = this.GetType().Assembly.GetManifestResourceStream("ocraext.ttf");
if (streamFont != null){
byte[] fontData = new byte[streamFont.Length];
streamFont.Read(fontData, 0, (int)streamFont.Length);
streamFont.Close();
unsafe{
fixed(byte *pFontData = fontData){
this.pfc.AddMemoryFont((System.IntPtr)pFontData, fontData.Length);
}
}
}else{
throw new Exception("Error! Could not read built-in Font.");
}
}catch(Exception eX){
throw new Exception("Exception was: " + eX.Message);
}
}
private void ConvertFontEnumToFloat(){
switch(this._fntSizeDefault){
case FontSize.Small :
this._fFontSize = 8.0F;
break;
case FontSize.Medium :
this._fFontSize = 10.0F;
break;
case FontSize.Large :
this._fFontSize = 12.0F;
break;
}
}
代码的典型调用将是这样的:
this.ConvertFontEnumToFloat();
this._fntOCRFont = new Font(this.pfc.Families[(int)FontEnum.OCR], this._fFontSize, System.Drawing.FontStyle.Bold);
if (this._fntOCRFont != null){
// Do something here... perhaps assign it to a control
}
函数InitOCRFont
使用unsafe,这意味着打开unsafe
编译器选项,从嵌入式资源读取并加载到PrivateFontCollection
。函数ConvertFontEnumToFloat
使用硬编码浮点值来指示基于字体枚举的大小。完成代码后,请务必在指定类的PrivateFontCollection
方法中处理Dispose
实例。