Load fonts on demand with the FontMissing event

View as Markdown

FontText

This 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

Download

Jost-Regular.ttf

Download

Montserrat-Medium.ttf

Download

Output

LoadFontsOnDemand.png

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