Search code examples
wpfdispatcherrendertransform

WPF resizing a canvas doesn't work in dispatcher


I am trying to resize a canvas using the following code but in the dispatcher. It doesn't seems to work am I missing something?

                    Dispatcher.BeginInvoke(new Action(() => {
                        canvas.RenderTransform = new ScaleTransform(scale, 
scale);
                        canvas.Measure(new Size(scale * w, scale * h));
                        canvas.Arrange(new Rect(0, 0, scale * w, scale * 
h));
                        canvas.UpdateLayout();

                        RenderTargetBitmap rtb = new RenderTargetBitmap(scale * w, scale * h, 96, 96, PixelFormats.Pbgra32);
                        rtb.Render(canvas);
                }), DispatcherPriority.Send);

            }

Solution

  • In order to create a bitmap from a Canvas with a scaled size you do not need to resize or scale the Canvas.

    Just create a VisualBrush from the Canvas and draw an appropriately sized rectangle with it into a DrawingVisual. Using a DrawingVisual also avoids any potential problems with margins and alignments.

    var width = canvas.ActualWidth * scale;
    var height = canvas.ActualHeight * scale;
    var visual = new DrawingVisual();
    
    using (var dc = visual.RenderOpen())
    {
        dc.DrawRectangle(new VisualBrush(canvas), null, new Rect(0, 0, width, height));
    }
    
    var rtb = new RenderTargetBitmap((int)width, (int)height, 96, 96, PixelFormats.Default);
    rtb.Render(visual);