我曾多次遇到用户未在其机器上安装 Windows Core 字体之一(例如 Courier New、Comic Sans MS、Arial)的问题。每当我尝试构建其中一种字体时,它都会抛出一个错误,而不是退回到相关的,或者实际上是任何其他字体。
如果我希望它是 Courier,但我不是特别喜欢它,那么构造字体的最佳方法是什么?
最佳答案
您可以将字体作为资源嵌入并使用 unsafe
关键字(并且必须使用'unsafe'进行编译)来获取字体...这是我用来设置用户的示例代码控制'OCR'类型的字体
private PrivateFontCollection pfc = new PrivateFontCollection(); private Font _fntOCRFont = null; private enum FontEnum{ OCR = 0 };
这声明了一个私有(private)字体集合...字体“OCR”作为资源嵌入使用命名约定,其中“foo”是一个命名空间,因此资源名称将是“foo.ocraext.ttf”。 .在此处查看“InitOCRFont”,它加载字体并将其添加到集合中:
private void InitOCRFont(){ try{ System.IO.Stream streamFont = this.GetType().Assembly.GetManifestResourceStream("foo.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("InitOCRFont Method - Exception occurred!\nException was: " + eX.Message); } }
在这里,我在用户控件中设置控件,通过遍历集合将字体设置为该“OCR”字体,请参见“InitializeCtlFont”,字体大小为 10 并且是粗体“type-face”:
private void InitializeCtlFont(){ this._fntOCRFont = new Font(this.pfc.Families[0], 10.0F, System.Drawing.FontStyle.Bold); if (this._fntOCRFont != null){ foreach(Control ctl in this.Controls){ if (ctl != null && ((ctl is Label) || (ctl is TextBox))){ ctl.Font = this._fntOCRFont; } } } }
当用户控件被处置时,必须释放字体占用的资源,如 Dispose
方法所示:
try{ if (this._fntOCRFont != null) this._fntOCRFont.Dispose(); }catch{ } try{ if (this.pfc != null) this.pfc.Dispose(); }catch{ }
希望对您有所帮助, 此致, 汤姆。
关于.net - DotNET 中的硬编码字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2392614/