Rendering a WPF visual object as the image has a solid black image

In a C # / WPF application, I have a DataChart object that I need to save for an image. Currently, the object is added to a fixed document and correctly displays this fixed document using the following code:

VisualBrush chartBrush = new VisualBrush(chart); Rectangle chartRect = new Rectangle(); chartRect.Height = chartClone.Height; chartRect.Width = chartClone.Width; chartRect.Fill = chartBrush; AddBlockUIElement(chartRect, textAlignment); 

However, instead of adding it as a block to a fixed document, now I just need to save the image to disk. I tried to do the following:

 RenderTargetBitmap bmp = new RenderTargetBitmap((int)chart.Width, (int)chart.Height, 96, 96, PixelFormats.Default); bmp.Render(chart); PngBitmapEncoder image = new PngBitmapEncoder(); image.Frames.Add(BitmapFrame.Create(bmp)); using (Stream fs = File.Create("TestImage.png")) { image.Save(fs); fs.Close(); } 

However, it just gives me a solid black image in the size of my chart, and I can’t understand why.

So my question is: does anyone know of a better way to turn a DataChart object into a PNG or BMP image that I can save? I tried to search when getting from VisualBrush or Rectangle to the image, but I didn’t find anything except the above, which seems to do what I need.

Thank you very much!

+4
source share
2 answers

See if you can work with the code below:

 VisualBrush target = new VisualBrush(element); DrawingVisual visual = new DrawingVisual(); DrawingContext dc = visual.RenderOpen(); dc.DrawRectangle(target, null, new Rect(0, 0, width, height)); dc.Close(); RenderTargetBitmap bmp = new RenderTargetBitmap( (int)width, (int)height, 96, 96, PixelFormats.Pbgra32); bmp.Render(visual); 
0
source

replace this line

 image.Frames.Add(BitmapFrame.Create(BitmapRender)); 

with such

 image.Frames.Add(BitmapFrame.Create(bmp)); 
0
source

All Articles