Load fonts on demand with the FontMissing event
View as MarkdownThis sample shows how to start with an empty font registry and add only the fonts a design actually uses, at the moment it asks for them. When a font is requested by a PostScript name that is not registered, CustomFontRegistry raises the FontMissing event; the handler looks the name up in the application's own font catalog and adds the file with CustomFontRegistry.Add, and the request then succeeds. A server with a large font library no longer has to parse every font at startup.
Code Snippet
// The application's font catalog: PostScript names and their files. Nothing is loaded yet.
var catalog = new Dictionary<string, string>
{
["Lobster"] = "Lobster.ttf",
["Jost-Regular"] = "Jost-Regular.ttf",
["Montserrat-Medium"] = "Montserrat-Medium.ttf",
};
using (var fontRegistry = new CustomFontRegistry())
{
fontRegistry.FontMissing += (sender, e) =>
{
if (catalog.TryGetValue(e.PostscriptName, out var fileName))
{
Console.WriteLine("Loading {0} from {1}", e.PostscriptName, fileName);
e.FontRegistry.Add(fileName);
}
};
using (var bitmap = new Bitmap(500, 200, PixelFormat.Format24bppRgb, RgbColor.White))
using (var graphics = bitmap.GetGraphics())
{
graphics.FontRegistry = fontRegistry;
// Each font is added the first time it is asked for.
var title = new PlainText("Summer Sale", graphics.CreateFont("Lobster", 60f))
{
Position = new System.Drawing.PointF(250, 95),
Alignment = TextAlignment.Center,
Brush = new SolidBrush(new RgbColor(214, 69, 65)),
};
var subtitle = new PlainText("Up to 50% off all items", graphics.CreateFont("Jost-Regular", 24f))
{
Position = new System.Drawing.PointF(250, 150),
Alignment = TextAlignment.Center,
};
graphics.DrawText(title);
graphics.DrawText(subtitle);
bitmap.Save("LoadFontsOnDemand.png");
}
Console.WriteLine("Fonts in the registry: {0} of {1}", fontRegistry.Fonts.Count, catalog.Count);
}
Input
Lobster.ttf
DownloadJost-Regular.ttf
DownloadMontserrat-Medium.ttf
DownloadOutput
LoadFontsOnDemand.png
LoadFontsOnDemand.txt
Loading Lobster from Lobster.ttf
Loading Jost-Regular from Jost-Regular.ttf
Fonts in the registry: 2 of 3
Used APIs
- Aurigma.GraphicsMill.Bitmap.GetGraphics
- Aurigma.GraphicsMill.Drawing.CustomFontRegistry
- Aurigma.GraphicsMill.Drawing.CustomFontRegistry.Add(String)
- Aurigma.GraphicsMill.Drawing.FontMissingEventArgs.FontRegistry
- Aurigma.GraphicsMill.Drawing.FontMissingEventArgs.PostscriptName
- Aurigma.GraphicsMill.Drawing.FontRegistry.Fonts
- Aurigma.GraphicsMill.Drawing.Graphics.CreateFont(String,Single)
- Aurigma.GraphicsMill.Drawing.Graphics.DrawText(Text)
- Aurigma.GraphicsMill.Drawing.Graphics.FontRegistry
- Aurigma.GraphicsMill.Drawing.PlainText
- Aurigma.GraphicsMill.Drawing.PlainText.Alignment
- Aurigma.GraphicsMill.Drawing.PlainText.Position
- Aurigma.GraphicsMill.Drawing.SolidBrush
- Aurigma.GraphicsMill.Drawing.Text.Brush
- Aurigma.GraphicsMill.Drawing.TextAlignment