简体   繁体   中英

WPF Toolkit Chart: How to save them as Image

I am basically looking to save chart as image to merge in my PDF report. I like the WPF Toolkit chart and can save image from them if they are displayed on Form. But, since I am working on background service, we don't have visual element to show up, and hence I have no clue how to save image, as my Image saving code :

renderBitmap = new RenderTargetBitmap(400, 400, 96, 96, PixelFormats.Pbgra32);
DrawingVisual isolatedVisual = new DrawingVisual();
drawing.DrawRectangle(new VisualBrush(mychart), null, new Rect(new Point(), bounds.Size));
renderBitmap.Render(isolatedVisual);

Gives black image only. HEre mychart is Chart control and if I add mychart to window it shows chart fine. So, I know the Chart control is working, just that it doesn't render when it is not on window.

EDIT: I also do

 mychart.Measure(size);
 mychart.Arrange(new Rect(size));
 mychart.UpdateLayout();

But still getting only blank image and control is not rendering on image.

I had the same problem with RenderTargetBitmap producing a black image.

I use this method:

public static void SaveAsImage(
    FrameworkElement element, 
    string filepath, 
    int width, 
    int height)
{
    element.Width = width;
    element.Height = height;
    element.Measure(new Size(width, height));
    element.Arrange(new Rect(0, 0, width, height));
    element.UpdateLayout();

    var target = new RenderTargetBitmap(
        width, height,
        96, 96, System.Windows.Media.PixelFormats.Pbgra32);

    target.Render(element);

    var encoder = new PngBitmapEncoder();
    var outputFrame = BitmapFrame.Create(target);
    encoder.Frames.Add(outputFrame);

    using (var file = File.OpenWrite(filepath))
    {
        encoder.Save(file);
    }
}

My problem was that my FrameworkeElement was a Window object, which had not been .Show()'ed before. There were no warnings or exceptions. Just the black image.

If I call .Show() then everything works as expected.

My solution is to change:

SaveToImage(view);

Into:

SaveToImage((FrameworkElement)view.Content);

This solved the problem in my case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM