Search code examples
c#wpfimagecanvasvisualbrush

Creating a VisualBrush without ever displaying the Visual it represents


Using the code below, I am attempting to fill a Canvas with UIElements and save it as a tif Image. However, my Image is always blank. It is because the Canvas is never displayed on the screen and some sort of initialization and drawing never took place? How can I make this work?

The Canvas creation would go something like this:

Canvas theCanvas = new Canvas();
theCanvas.Width = 2740;
theCanvas.Height = 2280;

...

Button button = new Button();
button.Content = "Push Me.";
button.Height = 50;
button.Width = 200;
Canvas.SetTop(button, 200);
Canvas.SetLeft(button, 300);
theCanvas.Children.Add(button);

To create the Image and save it:

using (System.IO.FileStream fs = 
           new System.IO.FileStream(path, System.IO.FileMode.Create))
{
    RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
        (int)inWidth,
        (int)inHeight, 1 / 300, 1 / 300, 
        PixelFormats.Pbgra32);

    DrawingVisual visual = new DrawingVisual();
    using (DrawingContext context = visual.RenderOpen())
    {
        VisualBrush brush = new VisualBrush(inCanvas);
        context.DrawRectangle(
            brush,
            null,
            new Rect(new Point(), new Size(inWidth, inHeight)));
    }                

    renderBitmap.Render(visual);

    BitmapEncoder encoder = new TiffBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
    encoder.Save(fs);
    fs.Close();
}

Solution

  • See first comment on my original post.