How to combine multiple System.Windows.Media.DrawingVisual object into one image in WPF?

1.1k views Asked by At

I have multiple functions which are returning System.Windows.Media.DrawingVisual object. I need to combine all the DrawingVisual object into one image.

private System.Windows.Media.DrawingVisual Shape1()
{
    DrawingVisual dv = new DrawingVisual();
    using (DrawingContext dc = dv.RenderOpen())
    {
        ////--- draw shapes on 'dc'
    }
    return dv;
}

private System.Windows.Media.DrawingVisual Shape2()
{
    DrawingVisual dv = new DrawingVisual();
    using (DrawingContext dc = dv.RenderOpen())
    {
        ////--- draw shapes on 'dc'
    }
    return dv;
}

In my function I need to combine the returned objects like the following

private void Combine()
{
    System.Windows.Media.DrawingVisual s1 = Shape1();
    System.Windows.Media.DrawingVisual s2 = Shape2();

    //--- here i need to draw the s1 & s2 into an image and display on screen.
}

One more way is, save all the DrawingVisuals into separate BitmapSource object then create one more DrawingVisual and draw all bitmap images on them. But its very complicated way. Is there any better way of doing this?

1

There are 1 answers

0
andrei.ciprian On

Refactor (extract method) the

draw shapes on 'dc'

part of your shape returning methods into Action<DrawingContext>.

Then use a sole DrawingContext to call all those actions upon, like below. Produce an ImageSource to assign to your Image control.

public static BitmapSource CreateBitmap(int width, int height, double dpi,
    IEnumerable<Action<DrawingContext>> renderActions)
{
    DrawingVisual drawingVisual = new DrawingVisual();

    using (DrawingContext drawingContext = drawingVisual.RenderOpen())
    {
        foreach (var render in renderActions)
            render(drawingContext);
    }

    RenderTargetBitmap bitmap = new RenderTargetBitmap(
        width, height, dpi, dpi, PixelFormats.Default);

    bitmap.Render(drawingVisual);

    return bitmap;
}