Combine shapes with boolean path operations
View as MarkdownThis sample shows how to build new shapes from existing ones with the boolean operations of the Path class: Path.Union, Path.Intersect, Path.Subtract, and Path.Xor. These static methods leave their arguments unchanged and return a new path, so the same two source shapes can be combined in several ways. The result is real vector geometry, so it can be filled, stroked, written to PDF, or used as a clipping path.
Code Snippet
var square = Path.Rectangle(20, 20, 120, 120);
var circle = Path.Ellipse(70, 70, 120, 120);
var operations = new (string Name, Path Result)[]
{
("Union", Path.Union(square, circle)),
("Intersect", Path.Intersect(square, circle)),
("Subtract", Path.Subtract(square, circle)),
("Xor", Path.Xor(square, circle)),
};
const float cellWidth = 220;
using (var bitmap = new Bitmap((int)cellWidth * operations.Length, 250, PixelFormat.Format24bppRgb, RgbColor.White))
using (var graphics = bitmap.GetGraphics())
{
var font = graphics.CreateFont("Arial", 18f);
for (int i = 0; i < operations.Length; i++)
{
float offsetX = i * cellWidth;
// The operations return new paths, so the source shapes can be reused for every cell.
var result = new Path(operations[i].Result);
result.Translate(offsetX, 0);
var sourceSquare = new Path(square);
sourceSquare.Translate(offsetX, 0);
var sourceCircle = new Path(circle);
sourceCircle.Translate(offsetX, 0);
graphics.FillPath(new SolidBrush(new RgbColor(46, 134, 222)), result);
graphics.DrawPath(new Pen(RgbColor.Gray, 1f), sourceSquare);
graphics.DrawPath(new Pen(RgbColor.Gray, 1f), sourceCircle);
var caption = new PlainText(operations[i].Name, font)
{
Position = new System.Drawing.PointF(offsetX + 105, 230),
Alignment = TextAlignment.Center,
};
graphics.DrawText(caption);
}
bitmap.Save("CombinePaths.png");
}
Output
CombinePaths.png
Used APIs
- Aurigma.GraphicsMill.Bitmap.GetGraphics
- Aurigma.GraphicsMill.Drawing.Graphics.CreateFont(String,Single)
- Aurigma.GraphicsMill.Drawing.Graphics.DrawPath(Pen,Path)
- Aurigma.GraphicsMill.Drawing.Graphics.DrawText(Text)
- Aurigma.GraphicsMill.Drawing.Graphics.FillPath(Brush,Path)
- Aurigma.GraphicsMill.Drawing.Path
- Aurigma.GraphicsMill.Drawing.Path.Ellipse(Single,Single,Single,Single)
- Aurigma.GraphicsMill.Drawing.Path.Intersect(Path,Path)
- Aurigma.GraphicsMill.Drawing.Path.Rectangle(Single,Single,Single,Single)
- Aurigma.GraphicsMill.Drawing.Path.Subtract(Path,Path)
- Aurigma.GraphicsMill.Drawing.Path.Translate(Single,Single)
- Aurigma.GraphicsMill.Drawing.Path.Union(Path,Path)
- Aurigma.GraphicsMill.Drawing.Path.Xor(Path,Path)
- Aurigma.GraphicsMill.Drawing.Pen
- Aurigma.GraphicsMill.Drawing.PlainText
- Aurigma.GraphicsMill.Drawing.PlainText.Alignment
- Aurigma.GraphicsMill.Drawing.PlainText.Position
- Aurigma.GraphicsMill.Drawing.SolidBrush
- Aurigma.GraphicsMill.Drawing.TextAlignment