#233 – An Example of Deriving from DrawingVisual Class

You can define a new class that inherits from the DrawingVisual class when you need a low-level control to draw one or more 2D objects.

Below is an example showing a simple implementation of a class derived from DrawingVisual that draws a couple of objects.

    class EllipseAndRectangle : DrawingVisual
        public EllipseAndRectangle()
            using (DrawingContext dc = RenderOpen())
                // Black ellipse with blue border
                    new Pen(Brushes.Blue, 3),        // Border
                    new Point(120, 120), 20, 40);    // Center & radius

                // Red rectangle with green border
                    new Pen(Brushes.Green, 4),       // Border
                    new Rect(new Point(10, 10), new Point(80, 80)));    // Corners

The RenderOpen method allows us to render content into the DrawingVisual object.  RenderOpen returns a DrawingContext, which allows us to draw various kinds of 2D objects.

The DrawingContext will actually cache all commands for drawing the objects that we tell it to draw.  This means that we only have to issue our drawing commands once–in the class’ constructor.