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.
The reason is that you’re not specifying any position in your
Rectconstructor, which therefore defaults to a position of(0,0).My suggestion for using
RenderTargetBitmapis to place yourCanvasinside aGrid, and then perform any explicit positioning required by your UI on this outerGrid, letting your innerCanvasnaturally assume a position of(0,0)within this parentGrid.For example, if you have:
Change it to:
Then, you could eliminate your calls to
MeasureandArrangealtogether. However, make sure that you still pass the childCanvasto yourRenderTargetBitmap.Rendermethod, not the parentGrid.