I am using GDI+ on the server-side to create an image which is streamed to the user's browser. None of the standard fonts fit my requirements and so I want to load a TrueType font and use this font for drawing my strings to the graphics object:
using (var backgroundImage = new Bitmap(backgroundPath))
using (var avatarImage = new Bitmap(avatarPath))
using (var myFont = new Font("myCustom", 8f))
{
Graphics canvas = Graphics.FromImage(backgroundImage);
canvas.DrawImage(avatarImage, new Point(0, 0));
canvas.DrawString(username, myFont,
new SolidBrush(Color.Black), new PointF(5, 5));
return new Bitmap(backgroundImage);
}
myCustom
represents a font that is not installed on the server, but for which I have the TTF file for.
How can I load the TTF file so that I can use it in GDI+ string rendering?
I've found a solution to using custom fonts.
// 'PrivateFontCollection' is in the 'System.Drawing.Text' namespace
var foo = new PrivateFontCollection();
// Provide the path to the font on the filesystem
foo.AddFontFile("...");
var myCustomFont = new Font((FontFamily)foo.Families[0], 36f);
Now myCustomFont
can be used with the Graphics.DrawString method as intended.