Convert a dashed stroke into filled shapes

View as Markdown

BitmapDrawingPath

This sample shows how to turn the stroke of a path into an outline that can be filled, measured, or combined with other shapes, like "Outline Stroke" in vector editors. Path.Widen takes everything from a Pen: its width, line caps, joins, and dash pattern, so every dash of a dashed line becomes a closed shape of its own. This is what cutting, engraving, and embroidery software needs, as it follows outlines and knows nothing about strokes. Path.GetArea then gives the area the stroke covers.

Code Snippet

var centerLine = new Path();
centerLine.MoveTo(40, 150);
centerLine.CurveTo(140, 20, 240, 280, 320, 150);
centerLine.CurveTo(400, 20, 500, 280, 600, 150);

var pen = new Pen(RgbColor.Black, 30f)
{
    LineCap = LineCap.Round,
    LineJoin = LineJoin.Round,
    DashPattern = new float[] { 60, 50 },
};

// Widen changes the path in place, so work on a copy.
var outline = new Path(centerLine);
outline.Widen(pen);

using (var bitmap = new Bitmap(640, 300, PixelFormat.Format24bppRgb, RgbColor.White))
using (var graphics = bitmap.GetGraphics())
{
    graphics.FillPath(new SolidBrush(new RgbColor(255, 214, 102)), outline);
    graphics.DrawPath(new Pen(new RgbColor(90, 60, 0), 2f), outline);
    graphics.DrawPath(new Pen(RgbColor.Red, 1f), centerLine);

    bitmap.Save("OutlineDashedStroke.png");
}

Console.WriteLine("Shapes: {0}", outline.Split().Length);
Console.WriteLine("Covered area: {0:F0} square pixels", outline.GetArea());

Output

OutlineDashedStroke.png

OutlineDashedStroke.png

OutlineDashedStroke.txt

Shapes: 6
Covered area: 15003 square pixels

Used APIs