I have a problem converting a canvas to a bitmap image in a C#/WPF app. Basically I have a canvas and the background of the canvas is a diagram of a piece of machinery. There are several coloured rectangles on the canvas which the user drags over the diagram to indicate areas of damage. My code redraws the rectangles on the fly as the mouse is moving and adds a rectangle as a child item when the mouse button is released. I then want to capture the diagram with the coloured rectangles as a new image to save to a DB. My problem is that when I convert it to a BMP all I see is the coloured rectangles with no background image. However, I need to see the rectangles and the background image together. I have posted in win forms rather than WPF as the issue is regarding code behind rather than XAML. Hope this is ok. Here is my code:
XAML for canvas and child rectangles:
<Canvas Height="421" Name="canv1">
<Rectangle.... etc/>
<Rectangle.... etc/>
<Rectangle.... etc/>
<Rectangle.... etc/>
<Rectangle.... etc/>
</Canvas>
code to assign canvas backgound image :
ImageBrush ib = new ImageBrush();
ib.ImageSource = backgroundImage;
canv1.background = ib;
my code to capture as bitmap (adapted from a post on stackoverflow)
public void ExportToPng(string path, Canvas diagram)
{
Transform transform = diagram.LayoutTransform;
diagram.LayoutTransform = null;
Size size = new Size(diagram.ActualWidth, diagram.ActualHeight);
diagram.Measure(size);
diagram.Arrange(new Rect(size));
RenderTargetBitmap renderBitmap =
new RenderTargetBitmap(
(int)size.Width,
(int)size.Height,
96d,
96d,
PixelFormats.Pbgra32);
renderBitmap.Render(diagram);
using (FileStream outStream = new FileStream( path, FileMode.Create))
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
encoder.Save(outStream);
}
many thanks for your help.