#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
                dc.DrawEllipse(Brushes.Black,
                    new Pen(Brushes.Blue, 3),        // Border
                    new Point(120, 120), 20, 40);    // Center & radius

                // Red rectangle with green border
                dc.DrawRectangle(Brushes.Red,
                    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.

About these ads

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 234 other followers

%d bloggers like this: