环境:Windows 7专业版,C#,WinForms
如果安装了字体,我成功使用Drawstring将文本字符串写入PictureBox。 < ==以下代码工作得很好......
我还希望能够从文件系统动态加载的字体文件中编写文本字符串(也就是说,未安装) &lt; ==下面的代码不工作...... < / EM>
理想情况下,我想支持TrueType和OpenType。
谢谢, 杰森
PointF pointF = new PointF(5, 5);
SolidBrush solidBrush = new SolidBrush(Color.Black);
FontFamily[] fontFamilies;
PrivateFontCollection privateFontCollection = new PrivateFontCollection();
// Add the font file to the private collection.
try
{
privateFontCollection.AddFontFile(FontFileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw;
}
fontFamilies = privateFontCollection.Families;
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
FontStyle[] fontStyles = { FontStyle.Regular, FontStyle.Bold, FontStyle.Italic, FontStyle.Bold | FontStyle.Italic,
FontStyle.Underline, FontStyle.Strikeout };
foreach (FontFamily fontFamily in fontFamilies)
{
foreach (FontStyle fontStyle in fontStyles)
{
if (fontFamily.IsStyleAvailable(fontStyle))
{
Font font = new Font(fontFamily.Name, NewFontSize, fontStyle, GraphicsUnit.Pixel);
//&lt;&lt; “font”加载为MS Sans Serif,如果未安装Font&gt;&gt;
Size fontDisplayDimensions = TextRenderer.MeasureText(SampleText, font);
// Draw sample text in font
e.Graphics.DrawString(SampleText, font, solidBrush, pointF);
// Move the starting point for the next FontFamily "down" for the just drawn font's height
pointF.Y += font.Height;
}
}
// Separate the families with white space.
pointF.Y += 10;
}