2

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;
}
Jason V
  • 837
  • 9
  • 18
  • Not sure what your issue is, everything regarding using the PrivateFontCollection looks good to me, but Fonts are disposable, so you might want to create it inside a using() statement... – Pete Mar 19 '13 at 19:29
  • Caveat for using non-installed fonts: Please note that the licensing issue around distributing non-free fonts with your software is very complex, and it’s potentially **very** expensive: most fonts that you buy for a few hundred bucks *cannot* be distributed with your software, this requires a separate, much more expensive license. – Konrad Rudolph Mar 19 '13 at 23:34
  • I'm not distributing any fonts. I just want to allow the user to use any fonts that they have locally. Thankfully, I don't have any responsibility for what they have on their machine. – Jason V Mar 27 '13 at 15:59

0 Answers0