Darren Young
Darren Young

Reputation: 11090

Saving Bitmap Moves The Canvas

I'm trying to save a canvas drawing as a bitmap. The code works fine, however once the drawing has been saved the canvas moves to the top left of the parent application. My code is as follows:

public void SaveBitmap()
    {
        Size size = new Size(canvas.ActualWidth, canvas.ActualHeight);
        canvas.Measure(size);
        canvas.Arrange(new Rect(size));

        RenderTargetBitmap renderBitmap =
            new RenderTargetBitmap(
                (int)size.Width,
                (int)size.Height,
                96d,
                96d,
                PixelFormats.Pbgra32);
        renderBitmap.Render(canvas);

        using (FileStream outStream = new FileStream("C:\\Users\\Darren\\Desktop\\test.bmp", FileMode.Create))
        {
            BmpBitmapEncoder encoder = new BmpBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
            encoder.Save(outStream);
        }


    }

The line that caused the problem is canvas.Arrange. Anybody shed any light?

Thanks.

Upvotes: 0

Views: 477

Answers (1)

Douglas
Douglas

Reputation: 54877

The reason is that you’re not specifying any position in your Rect constructor, which therefore defaults to a position of (0,0).

My suggestion for using RenderTargetBitmap is to place your Canvas inside a Grid, and then perform any explicit positioning required by your UI on this outer Grid, letting your inner Canvas naturally assume a position of (0,0) within this parent Grid.

For example, if you have:

<Window>
    <Canvas Left="10" Top="30" />
</Window>

Change it to:

<Window>
    <Grid Left="10" Top="30">
        <Canvas />
    </Grid>
</Window>

Then, you could eliminate your calls to Measure and Arrange altogether. However, make sure that you still pass the child Canvas to your RenderTargetBitmap.Render method, not the parent Grid.

Upvotes: 3

Related Questions