Drawing shapes and text on images

 
 
  • Gérald Barré

In this post, we'll explore Meziantou.Framework.Imaging and Meziantou.Framework.Fonts. These packages, under MIT license, allow you to draw shapes, paths, gradients, and text on images, to read font files and shape text in any script, and to convert colors between ICC profiles.

The overview of Meziantou.Framework.Imaging showed what the package can do, and the previous post covered loading, converting, and resizing images. This one is about creating pixels. The text is the hard part: the result depends on the fonts installed on the machine, and on a text engine that must join the letters of Arabic and reorder the vowel signs of Hindi. Here, the drawing code, the font reader, and the text shaper are written in C#, and a text is drawn with the font files you give, so it doesn't depend on the machine. Typical use cases are:

  • Generating social media cards, certificates, badges, or charts on a server
  • Adding a caption or a watermark to photos
  • Drawing translated texts in any script: Arabic, Hebrew, Hindi, Chinese, with mixed directions
  • Reading font files and shaping text, to write your own text renderer or document writer
  • Drawing brand colors on wide-gamut photos, and converting colors between ICC profiles

#Installation

Shell
dotnet package add Meziantou.Framework.Imaging

Meziantou.Framework.Imaging depends on Meziantou.Framework.Fonts, so you can also use the font API without adding another package. The canvas, brushes, pens, and paths are in the Meziantou.Framework.Imaging.Drawing namespace, the fonts and the text layout in Meziantou.Framework.Imaging.Typography, the ICC profiles in Meziantou.Framework.Imaging.Metadata, and the color transforms in Meziantou.Framework.Imaging. The low-level font API is in the Meziantou.Framework.Fonts namespace.

#Drawing shapes

Draw gives you a canvas in a callback. Each call paints over what is already there, in order:

C#
using var image = new Image<Rgba32>(400, 200);

// Brushes, pens, and paths are immutable: create them once and reuse them
var background = new LinearGradientBrush(new PointD(0, 0), new PointD(400, 200), [
    new GradientStop(0, Rgba32.ParseHex("#2B5876")),
    new GradientStop(1, Rgba32.ParseHex("#4E4376"))]);
var ring = new Pen(Colors.White, 4);
var rule = new Pen(new Rgba32(255, 255, 255, 160), 2) { DashPattern = [6, 4] };

image.Draw(canvas =>
{
    canvas.FillRoundedRectangle(background, new RectangleD(0, 0, 400, 200), 16);
    canvas.FillRoundedRectangle(Colors.Gold, new RectangleD(24, 24, 120, 40), 12);
    canvas.StrokeCircle(ring, new PointD(320, 100), 50); // The pen is centered on the circle
    canvas.StrokeLine(rule, new PointD(24, 160), new PointD(376, 160));
});

image.Save("card.png");

Console.WriteLine(image.Frames[0][0, 0]);   // Rgba32(0, 0, 0, 0): outside the rounded corner
Console.WriteLine(image.Frames[0][30, 30]); // Rgba32(255, 215, 0, 255): Colors.Gold

A card with a gradient from blue to purple, a gold rounded rectangle, a white ring, and a dashed linecard.png

A few things to know about the canvas:

  • The canvas is only valid inside the callback. image.Draw paints every frame of an animation the same way; image.Frames[i].Draw paints one frame, so you can draw something different on each frame.
  • Coordinates are double values, with the origin at the top-left corner. Integer coordinates are the boundaries between pixels, so a rectangle on integer coordinates has sharp edges, and a line of 1 pixel is crisp when it goes through the middle of a row, at y + 0.5.
  • A color, such as Colors.Gold (the named colors of CSS), converts to a solid brush.
  • The canvas has the usual shapes: rectangles, rounded rectangles, ellipses, polygons, pie slices, arcs, Bézier curves, and smooth curves through a list of points for charts. A Pen has a width, joins, caps, dashes, and markers such as arrow heads.

Draw also accepts a CancellationToken. Use it when the shapes come from untrusted input: the time a shape takes grows with its number of edges, and a short dash pattern on a large canvas makes millions of dashes.

#Paths, SVG icons, and boolean operations

Any other shape is a VectorPath. VectorPathBuilder builds one with MoveTo, LineTo, QuadraticBezierTo, CubicBezierTo, ArcTo, and Close, and VectorPath.ParseSvgPathData reads the d attribute of an SVG path element, which is the format most icons come in. Paths can be transformed and combined:

C#
// The "d" attribute of the path of an SVG icon of 24x24 pixels
var heart = VectorPath.ParseSvgPathData("M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z");

// Scale the path, not the pixels: the curves stay curves
var icon = heart.Transform(AffineTransform.CreateScale(4, 4));

// A disk with the heart cut out of it
var disk = new VectorPathBuilder().AddCircle(new PointD(48, 48), 46).Build();
var badge = disk.Combine(icon, PathCombineMode.Exclude);

Console.WriteLine(badge.Contains(new PointD(48, 48), FillRule.NonZero)); // False: the center is in the heart
Console.WriteLine(badge.Contains(new PointD(10, 48), FillRule.NonZero)); // True

using var image = new Image<Rgba32>(96, 96);
image.Draw(canvas => canvas.Fill(Colors.Crimson, badge));
image.Save("badge.png");

A crimson disk with a transparent heart cut out of itbadge.png: the heart is transparent

The parser is strict: invalid path data throws a FormatException that gives the position of the error, where a browser would silently draw the part before it. TryParseSvgPathData returns false instead, and ToSvgPathData writes a path back in the same format.

Combine supports Union, Intersect, Exclude, and Xor, and returns a path you can draw, combine, or measure again. Paths have other operations that are tedious to write yourself: Offset grows or shrinks a shape (the border of a sticker), RoundCorners rounds the corners of a polygon, GetLength, TryGetPointAtDistance, and Trim measure and cut a path (a progress gauge, an arrow head at the end of a curve), and Contains and StrokeContains test whether a point is inside a shape or on its outline.

#Gradients and brushes

Besides solid colors, a shape can be filled with a linear, radial, or sweep (conic) gradient, a gradient across the corners of a polygon (PathGradientBrush), a mesh gradient, an image (ImageBrush), or a repeated pattern (PatternBrush). Gradients have a detail that matters more than it looks: the color space in which the colors of two stops are mixed. This sample reads the pixel in the middle of a gradient from red to green:

C#
GradientColorSpace[] colorSpaces = [GradientColorSpace.Encoded, GradientColorSpace.LinearSrgb, GradientColorSpace.Oklab];
foreach (var colorSpace in colorSpaces)
{
    // From red to green over 101 pixels: the center of the pixel 50 is half way
    var brush = new LinearGradientBrush(new PointD(0.5, 0), new PointD(100.5, 0), [
        new GradientStop(0, new Rgba32(255, 0, 0)),
        new GradientStop(1, new Rgba32(0, 255, 0))])
    {
        ColorSpace = colorSpace,
    };

    using var image = new Image<Rgba32>(101, 1);
    image.Draw(canvas => canvas.Fill(brush));
    Console.WriteLine($"{colorSpace}: {image.Frames[0][50, 0]}");
}

// Encoded: Rgba32(128, 128, 0, 255)
// LinearSrgb: Rgba32(188, 188, 0, 255)
// Oklab: Rgba32(208, 168, 0, 255)

Here is the same gradient over 290 pixels, in each color space:

The gradient from red to green in the Encoded, LinearSrgb, and Oklab color spacesThe gradient from red to green in each color space

Encoded, the default, averages the stored sample values: the middle is a dark olive. LinearSrgb mixes the light, which gives a brighter yellow. Oklab mixes in a space where lightness and hue change evenly, which avoids the dull band between two saturated colors. On 8-bit images, a slow gradient between two close colors shows bands; set Dither on the brush to hide them.

#Layers

Draw two translucent shapes that overlap, and you see the overlap: each shape lets the other one show through. That is rarely what you want for a logo or an icon faded into a background. A layer solves this: the callback draws on a transparent image, which is then drawn on the canvas as a whole, with its opacity:

C#
using var image = new Image<Rgba32>(320, 140, Colors.WhiteSmoke);
var translucent = new Rgba32(220, 20, 60, 128); // Crimson at 50%

image.Draw(canvas =>
{
    // Without a layer: each disk is translucent, so they show through each other
    canvas.FillCircle(translucent, new PointD(60, 70), 40);
    canvas.FillCircle(translucent, new PointD(110, 70), 40);

    // With a layer: the disks are drawn opaque, then faded together
    canvas.Layer(0.5, layer =>
    {
        layer.FillCircle(Colors.Crimson, new PointD(210, 70), 40);
        layer.FillCircle(Colors.Crimson, new PointD(260, 70), 40);
    });
});

image.Save("layers.png");

Two pairs of overlapping pink disks: the first pair has a darker overlap, the second pair is one uniform shapelayers.png: without a layer, then with a layer

Most effects of the canvas work the same way: they take a callback, and apply to what it draws as a whole. Shadow draws the shadow of everything the callback draws, Clip keeps the drawings inside a shape, and Blur blurs them:

C#
using var image = new Image<Rgba32>(320, 160, Colors.WhiteSmoke);
var card = new RectangleD(40, 30, 240, 90);
var shape = new VectorPathBuilder().AddRoundedRectangle(card, 16).Build();
var light = new SolidBrush(new Rgba32(255, 255, 255, 110)) { BlendMode = BlendMode.SoftLight };

image.Draw(canvas =>
{
    // The card, with the shadow of everything drawn in the callback
    canvas.Shadow(new Rgba32(0, 0, 0, 90), new PointD(0, 8), 8, shadowed =>
        shadowed.Fill(Colors.RoyalBlue, shape));

    // A light that stays inside the card
    canvas.Clip(shape, inside => inside.FillEllipse(light, new PointD(160, 30), 160, 40));

    // A glow: a blurred disk
    canvas.Blur(6, glow => glow.FillCircle(Colors.Gold, new PointD(80, 75), 16));
});

image.Save("layer-effects.png");

A blue card with rounded corners and a soft shadow, a light band across its top, and a blurred yellow glowlayer-effects.png

Effects nest in any order. The canvas also has masks, color filters, the filters of CSS and SVG, blend modes, and drawing of other images, including on a quadrilateral in perspective. The documentation lists them all.

#Drawing text

Font.Load reads a TrueType, OpenType, WOFF, or WOFF2 file. Text is drawn in two steps: TextLayout.Create lays out the text, and FillText draws the layout. Because the layout is what is drawn, it is also what you measure to place the text:

C#
// TrueType, OpenType, WOFF, and WOFF2: the format comes from the content of the file
var font = Font.Load("NotoSans-Regular.ttf");

// A layout holds the glyphs of the text and their positions: it is what you measure and what you draw
var label = TextLayout.Create("Download", font, size: 20);

using var image = new Image<Rgba32>(240, 64, Colors.White);
image.Draw(canvas =>
{
    var button = new RectangleD(20, 12, 200, 40);
    canvas.FillRoundedRectangle(Colors.SteelBlue, button, radius: 8);

    // Center what is drawn (the ink), not the line box, in the button
    var origin = label.GetOrigin(button, TextHorizontalAnchor.Center, TextVerticalAnchor.Center, TextBounds.Ink);
    canvas.FillText(Colors.White, label, origin);
});

image.Save("button.png");

A blue button with the white text Download centered in itbutton.png

The size is in pixels per em, not in points. A Font is immutable and thread-safe: load it once and share it. TextBounds.Ink centers the visible shape of the text; the default, TextBounds.Layout, uses the ascent and the descent of the font, which is what you want to line up several texts.

For longer texts, a RichTextBuilder gives each part of the text its own style, and TextLayoutOptions say how the lines are wrapped, aligned, and cut:

C#
var font = Font.Load("NotoSans-Regular.ttf");
var regular = new TextStyle(font, 16);
var highlight = new TextStyle(font, 16) { Brush = new SolidBrush(Colors.Crimson), Decorations = TextDecorations.Underline };

// The layout wraps the whole text, not each span
var text = new RichTextBuilder()
    .Append("The layout wraps the text where ", regular)
    .Append("Unicode", highlight)
    .Append(" allows a line break, and cuts it after two lines with an ellipsis when it does not fit in the card.", regular)
    .Build();

var layout = TextLayout.Create(text, new TextLayoutOptions
{
    MaxWidth = 260,
    MaxLines = 2,
    Trimming = TextTrimming.Word,
});

Console.WriteLine($"{layout.LineCount} lines, truncated: {layout.IsTruncated}"); // 2 lines, truncated: True

using var image = new Image<Rgba32>(280, (int)Math.Ceiling(layout.Height) + 20, Colors.White);
image.Draw(canvas => canvas.FillText(Colors.Black, layout, new PointD(10, 10)));
image.Save("paragraph.png");

Two lines of text, with the word Unicode in red and underlined, ending with an ellipsisparagraph.png: the text is cut after two lines

Lines are wrapped where the Unicode line breaking algorithm allows it. IsTruncated tells you that a part of the text is not drawn, so you can show the whole text elsewhere, in a tooltip for instance.

A word longer than the line, such as a reference or a hash, overflows the box by default. Choose what to break, as with the overflow-wrap and word-break properties of CSS:

C#
var font = Font.Load("NotoSans-Regular.ttf");
var style = new TextStyle(font, 15);
var text = "Your order 7F3A9C2E8B1D4F6A0E5C has been shipped";

TextLayoutOptions[] options =
[
    new() { MaxWidth = 140 },                                           // The long word overflows the box
    new() { MaxWidth = 140, OverflowWrap = TextOverflowWrap.Anywhere }, // Only the long word is broken
    new() { MaxWidth = 140, WordBreak = TextWordBreak.BreakAll },       // Any word can be broken
];

using var image = new Image<Rgba32>(600, 130, Colors.White);
image.Draw(canvas =>
{
    for (var i = 0; i < options.Length; i++)
    {
        var layout = TextLayout.Create(text, style, options[i]);
        var origin = new PointD(20 + i * 200, 20);

        // The box the text must fit in
        canvas.StrokeRectangle(new Pen(Colors.LightSteelBlue, 1), new RectangleD(origin.X - 0.5, origin.Y - 0.5, 141, 91));
        canvas.FillText(Colors.Black, layout, origin);
    }
});

image.Save("word-break.png");

The same text in three boxes: the long reference overflows the first box, is broken in the second box, and every word can be broken in the third boxword-break.png: Normal, OverflowWrap.Anywhere, and WordBreak.BreakAll

OverflowWrap.Anywhere only breaks a word when it cannot fit on a line, while WordBreak.BreakAll fills each line, even if it cuts short words. The options also cover justification, hyphenation, tab stops, a line breaking that balances the lines of a paragraph (TextLineBreakStrategy.Optimal), and vertical text. TextLayout.CreateToFit finds the largest size at which a text fits in a box, which is what a title on a card needs.

A text can also follow a path. Pass a VectorPath to FillText instead of a position, and each character is placed on the path and turned to its direction. The characters are not bent: they spread on the outside of a curve, and get closer on the inside. The pale line is the path, drawn to show it:

C#
var font = Font.Load("NotoSans-Regular.ttf");
var text = TextLayout.Create("Text can follow any path", font, size: 28);

// A wave, from left to right
var wave = new VectorPathBuilder()
    .MoveTo(new PointD(20, 100))
    .CubicBezierTo(new PointD(140, 0), new PointD(260, 180), new PointD(380, 80))
    .Build();

using var image = new Image<Rgba32>(400, 160, Colors.White);
image.Draw(canvas =>
{
    canvas.Stroke(new Pen(Colors.LightSteelBlue, 2), wave);
    canvas.FillText(Colors.Crimson, text, wave, new TextPathOptions
    {
        Alignment = TextPathAlignment.Center, // The middle of the text is at the middle of the path
        BaselineOffset = 6,                   // Draws the text 6 pixels above the path
    });
});

image.Save("text-path.png");

The text "Text can follow any path" in red, drawn along a wavetext-path.png

TextPathOptions places the text on the path. StartOffset moves it along the path, and Side draws it on the other side, following the path from its end to its start. A text longer than the path continues straight by default; set Overflow to TextPathOverflow.Clip to cut it. StrokeText has the same overload, to draw only the outlines of the characters.

#Complex scripts and fallback fonts

A font rarely has every character. A FontStack is a list of fonts: each character is drawn with the first font that has it. The layout also orders the text with the Unicode Bidirectional Algorithm, and shapes each run with the OpenType tables of its font:

C#
// Each character is drawn with the first font of the stack that has it
var fonts = new FontStack(
    Font.Load("NotoSans-Regular.ttf"),
    Font.Load("NotoNaskhArabic-Regular.ttf"),
    Font.Load("NotoSansDevanagari-Regular.ttf"));

var layout = TextLayout.Create("Hello, مرحبا, नमस्ते!", new TextStyle(fonts, 32));
Console.WriteLine(layout.HasMissingGlyphs); // False

using var image = new Image<Rgba32>((int)Math.Ceiling(layout.Width) + 20, (int)Math.Ceiling(layout.Height) + 20, Colors.White);
image.Draw(canvas => canvas.FillText(Colors.Black, layout, new PointD(10, 10)));
image.Save("hello.png");

// No font of the stack has these ideographs: they are drawn with the missing glyph, and nothing throws
Console.WriteLine(TextLayout.Create("世界", new TextStyle(fonts, 32)).HasMissingGlyphs); // True

The text Hello, followed by an Arabic word and a Hindi wordhello.png

In the result, the Arabic word is written from right to left inside a left-to-right paragraph, its letters are joined, and the consonants of "नमस्ते" are combined into a conjunct. Check HasMissingGlyphs when the text comes from a user: a character that no font has is drawn with the missing glyph of the first font, without any exception.

Using only the fonts you give is what makes the output identical on every machine. When you prefer to use the fonts of the machine, Font.LoadInstalled("Arial", weight: 700) finds an installed family and returns null when it is not installed, and fonts.WithInstalledFallback() searches the installed fonts for the characters the stack doesn't have. The text API also supports variable fonts (Font.WithVariations), color fonts such as emoji fonts, OpenType features (new FontFeature("smcp") for small capitals), and outlines with StrokeText or TextLayout.ToPath. Like images, font files are untrusted input: the work to decode a glyph is bounded by ImageResourceLimits.MaxGlyphComplexity.

#Shaping text with Meziantou.Framework.Fonts

Meziantou.Framework.Fonts is the engine under the text API, and it is also used by the browser engine of Meziantou.Framework.WebPlatform. You need it directly when you write your own text renderer or document writer, and you want the glyphs of a text and their positions. Shaping is the step that makes complex scripts work: the characters of the text are not the glyphs of the font. For instance, in the Hindi syllable "क्षि", the vowel sign is typed last, but drawn first:

C#
// The limits that protect the application from hostile fonts, and the memory of the temporary buffers
var environment = new PooledFontEnvironment(FontResourceLimits.Default, maxLiveAllocationBytes: 64 * 1024 * 1024);
using var stream = File.OpenRead("NotoSansDevanagari-Regular.ttf");
var face = FontLoader.Load(stream, environment)[0]; // A font collection has several faces

// "kshi": the consonant क, a virama, the consonant ष, and the vowel sign ि
var text = "क्षि";
var buffer = new GlyphBuffer(face.Data.Limits);
TextShaper.AddText(buffer, text);
TextShaper.Shape(buffer, face, UnicodeScript.Devanagari, OpenTypeLanguage.GetTags("hi"), isRightToLeft: false, features: []);

Console.WriteLine($"{text.Length} characters, {buffer.Length} glyphs"); // 4 characters, 2 glyphs
for (var i = 0; i < buffer.Length; i++)
{
    // Advances are in font units; the cluster is the index of the first character the glyph comes from
    Console.WriteLine($"glyph {buffer.Info[i].Glyph}, cluster {buffer.Info[i].Cluster}, advance {buffer.Positions[i].XAdvance}");
}

// glyph 551, cluster 0, advance 259
// glyph 90, cluster 0, advance 717

Console.WriteLine(face.MapCodePoint('ि')); // 32: the glyph of the vowel sign in the character map

The glyph numbers are those of Noto Sans Devanagari 2.006. The 4 characters become 2 glyphs. The first one is the vowel sign, moved before the consonants. It is not the glyph of the character map (32), but a form the font chose for this conjunct: before the consonant क alone, the same font uses glyph 545. The second glyph is the conjunct क्ष, one glyph for three characters. Both glyphs belong to cluster 0, so a caret, a selection, or a line break never separates them. Mapping each character to its glyph with MapCodePoint and drawing them in order would give a broken word.

The package implements the GSUB and GPOS tables and the shaping models of complex scripts: Arabic, Hebrew, the Indic scripts, Khmer, Myanmar, Thai and Lao, Hangul, the Universal Shaping Engine, and the tables of fonts made for Apple systems. According to its documentation, the result is checked against HarfBuzz. TextShaper.SplitRuns splits a line into runs of one script and one direction, and FontFace.DecodeOutline gives the outline of each glyph, as lines and Bézier curves, to an OutlineSink you implement, for instance to build a path in your own format. The package also lists the fonts installed on Windows, macOS, and Linux (SystemFontCollection), creates subsets of fonts to embed them in a document (FontSubsetter), and reads AFM files, the metrics of PostScript fonts such as the 14 standard fonts of PDF.

#Converting colors with ICC profiles

The samples of an image only mean a color together with a description of its color space, usually an ICC profile. The previous post showed ConvertColorProfile, which converts the pixels of an image to another profile. Drawing raises the same question: on a photo labeled with the Display P3 profile, as the photos of recent phones are, (255, 0, 0) is the most saturated red of Display P3, not the red of sRGB. When you draw a brand color defined in CSS, you want the color, not the sample values:

C#
// A photo labeled with the Display P3 profile, as the photos of recent phones are
using var photo = Image.Load<Rgb24>("photo.jpg");

photo.Draw(canvas =>
{
    // Sample values: the most saturated red of Display P3
    canvas.FillRectangle(new Rgba32(255, 0, 0), new RectangleD(0, 0, 10, 10));

    // A color of sRGB, as in CSS or a design tool: converted to the color space of the photo
    canvas.PaintProfile(IccProfile.Srgb, srgb => srgb.FillRectangle(new Rgba32(255, 0, 0), new RectangleD(10, 0, 10, 10)));
});

Console.WriteLine(photo.Frames[0][5, 5]);  // Rgb24(255, 0, 0)
Console.WriteLine(photo.Frames[0][15, 5]); // Rgb24(234, 51, 35): the red of sRGB, in Display P3

Inside PaintProfile, the colors of the brushes, gradients, shadows, and texts are converted to the color space of the image, and the photo keeps its profile. Images drawn on the canvas are not converted: convert them with ConvertColorProfile first.

To convert your own buffers, IccColorTransform converts interleaved samples between two profiles: 8-bit, 16-bit, or floating-point, CMYK included. Wide-gamut profiles have colors that sRGB cannot show, and the transform must do something with them:

C#
// A transform is immutable and thread-safe: create it once for a pair of profiles, and reuse it
var clip = IccColorTransform.Create(IccProfile.DisplayP3, IccProfile.Srgb, IccColorTransformOptions.Default);
var reduceChroma = IccColorTransform.Create(IccProfile.DisplayP3, IccProfile.Srgb, new IccColorTransformOptions
{
    GamutMapping = GamutMapping.ReduceChroma,
});

// Interleaved samples without alpha: here, one RGB color, the most saturated red of Display P3
byte[] p3Red = [255, 0, 0];
var srgb = new byte[3];

clip.Convert(p3Red, srgb);
Console.WriteLine(string.Join(", ", srgb)); // 255, 0, 0

reduceChroma.Convert(p3Red, srgb);
Console.WriteLine(string.Join(", ", srgb)); // 255, 11, 12

By default, each channel is clipped, which can change the hue of a saturated color. GamutMapping.ReduceChroma reduces its chroma at constant lightness and hue instead, with the gamut mapping algorithm of CSS Color 4. IccColorTransformOptions also selects the rendering intent and the black point compensation, which matter for printer profiles. The same options apply to the other conversions: CMYK images can be loaded with their inks (Cmyk32) or converted to RGB, and HDR images that use the PQ or HLG transfer functions can be tone mapped to a standard profile with HdrToneMappingOptions.

#Additional resources

This post is part of the series 'Exploring Meziantou.Framework'. Be sure to check out the rest of the blog posts of the series!

Show the 20 posts of the series

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?