Environment: Windows 7 Pro, C#, WinForms
I am successfully using Drawstring to write a text string to a PictureBox if the font is installed. <== Code below is working just fine...
I also want to be able to write a text string from a font file that is dynamically loaded from the filesystem (aka, not installed) <== Code below is NOT Working...
Ideally, I want to support both TrueType and OpenType.
Thanks, Jason
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" Loads as MS Sans Serif, if Font is not installed >>
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;
}