#236 – Drawing an Arbitrary Geometry into a DrawingVisual

You can render content in a DrawingVisual object by using a DrawingContext to draw objects that you want rendered.  Use the DrawingContext‘s DrawGeometry method to draw an arbitrary geometry.

Below is an example of using DrawGeometry, where we render our object in the DrawingVisual constructor.

        public MyDrawingVisual()
            // First define the geometric shape
            StreamGeometry geom = new StreamGeometry();
            using (StreamGeometryContext gc = geom.Open())
                // Start new object, filled=true, closed=true
                gc.BeginFigure(new Point(150.0, 150.0), true, true);

                // isStroked=true, isSmoothJoin=true
                gc.LineTo(new Point(210.0, 105.0), true, true);
                gc.LineTo(new Point(270.0, 150.0), true, true);
                gc.LineTo(new Point(270.0, 45.0), true, true);
                gc.LineTo(new Point(210.0, 90.0), true, true);
                gc.LineTo(new Point(150.0, 45.0), true, true);

            using (DrawingContext dc = RenderOpen())
                // Draw our geometry
                dc.DrawGeometry(Brushes.DarkRed, new Pen(Brushes.Blue, 2), geom);

We create a new StreamGeometry object, which is what we’ll render into the DrawingContext using the DrawGeometry method.  To create the actual object, we use the StreamGeometryContext of the StreamGeometry and call methods like BeginFigure and LineTo.


Get every new post delivered to your Inbox.

Join 446 other followers