环境:Windows 7 Pro、C#、WinForms
如果安装了字体,我成功地使用 Drawstring 将文本字符串写入 PictureBox。 <== 下面的代码工作得很好......
我还希望能够从从文件系统(又名,未安装)动态加载的字体文件中写入文本字符串 <== 下面的代码不起作用...
理想情况下,我想同时支持 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);
// << "font" 加载为 MS Sans Serif,如果 Font 没有安装 >>
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;
}