NoName
NoName

Reputation: 8025

WPF DrawingContext: How to keep existing content when draw new content?

I have a DrawingVisual and want to draw a grape tree, show to screen then after that, draw a fox. Like this:

public class Gif : DrawingVisual
{
    void Draw_Geometry(Geometry geo)
    {
        using (DrawingContext dc = RenderOpen())
        {
            dc.DrawGeometry(Brushes.Brown, new Pen(Brushes.Brown, 0), geo);
        }
    }

    void Draw_Grape ()
    {
        Draw_Geometry(grape);
    }

    void Draw_Fox ()
    {
        Draw_Geometry(fox);
    }
}

Problem is when call Draw_Fox (), the DrawingContext auto clear existing grape tree. So I want to ask how to keep existing drawing content when draw new geometry? Thank!

Upvotes: 4

Views: 2953

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70661

From the documentation:

When you call the Close method of the DrawingContext, the current drawing content replaces any previous drawing content defined for the DrawingVisual. This means that there is no way to append new drawing content to existing drawing content.

I feel like that's pretty clear. It is not possible to do literally what you ask. Opening the visual for rendering will always end up with the new rendering replacing whatever was there before.

If you want to append the current rendering, you need to include it explicitly. For example:

void Draw_Geometry(Geometry geo)
{
    using (DrawingContext dc = RenderOpen())
    {
        dc.DrawDrawing(Drawing);
        dc.DrawGeometry(Brushes.Brown, new Pen(Brushes.Brown, 0), geo);
    }
}

Upvotes: 2

Related Questions