Alan Spark
Alan Spark

Reputation: 8292

Draw XAML shapes to DrawingContext?

I have several common symbols that have been composed of WPF shape primatives (e.g. Rectangle, Line, Path etc). These symbols are currently stored in xaml files as user controls. For example:

<Canvas x:Name="Symbol" Width="100" Height="100">
    <Rectangle x:Name="Rectangle" Width="100" Height="100" Stretch="Fill">
        <Rectangle.Fill>
            <SolidColorBrush Color="Aqua"></SolidColorBrush>
        </Rectangle.Fill>
    </Rectangle>
</Canvas>

The above is a simple example but most of my symbols are more complex and composed of many different parts. So, I was hoping to use these user controls to store the symbols and make them easy to manipulate.

I am doing quite a bit of drawing in the OnRender method of a Canvas and would like to include some of these composite symbols in my drawing. Is it possible get these into a format to draw them to the DrawingContext? I am aware that there is a method called DrawingContext.DrawImage but this takes an ImageSource as input.

Any ideas would be much appreciated.

Thanks, Alan

Upvotes: 2

Views: 2691

Answers (1)

Rune Andersen
Rune Andersen

Reputation: 1705

You can use drawimage if you make your canvas into an imagesource like:

VisualBrush vb = new VisualBrush(canvas);
GeometryDrawing gd = new GeometryDrawing(vb, new Pen(Brushes.Transparent, 0), new RectangleGeometry(new Rect(0, 0, width, height)));
img = new DrawingImage(gd);

Upvotes: 5

Related Questions