简体   繁体   English

WPF工具包图表:如何将它们另存为图像

[英]WPF Toolkit Chart: How to save them as Image

I am basically looking to save chart as image to merge in my PDF report. 我基本上希望将图表另存为图像以合并到我的PDF报告中。 I like the WPF Toolkit chart and can save image from them if they are displayed on Form. 我喜欢WPF工具包图表,如果将它们显示在窗体上,则可以保存其中的图像。 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. 这里的mychart是Chart控件,如果我将mychart添加到窗口中,它会很好地显示图表。 So, I know the Chart control is working, just that it doesn't render when it is not on window. 因此,我知道Chart控件正在工作,只是当它不在窗口中时它不会呈现。

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. RenderTargetBitmap产生黑色图像时,我遇到了同样的问题。

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. 我的问题是我的FrameworkeElement是一个Window对象,之前没有.Show()。 There were no warnings or exceptions. 没有警告或例外。 Just the black image. 只是黑色图像。

If I call .Show() then everything works as expected. 如果我调用.Show(),那么一切都会按预期进行。

My solution is to change: 我的解决方案是更改:

SaveToImage(view);

Into: 成:

SaveToImage((FrameworkElement)view.Content);

This solved the problem in my case. 这解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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