Home > database >  Export chart to PNG without rendering it in the UI - WPF LiveCharts2
Export chart to PNG without rendering it in the UI - WPF LiveCharts2

Time:11-03

I'm trying to export a chart as a PNG file (without having to render it in the UI) and have implemented the following code for LiveCharts v0 which works fine...

LiveCharts.Wpf.CartesianChart control = new LiveCharts.Wpf.CartesianChart()
{
// Series = ...
Width = 700,
Height = 700,
DisableAnimations = true
};

var viewbox = new Viewbox();
viewbox.Child = control;
viewbox.Measure(control.RenderSize);
viewbox.Arrange(new Rect(new System.Windows.Point(0, 0), control.RenderSize));
control.Update(true, true); //force chart redraw
viewbox.UpdateLayout();

var encoder = new PngBitmapEncoder();
var bitmap = new RenderTargetBitmap((int)control.ActualWidth, (int)control.ActualHeight, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(control);
var frame = BitmapFrame.Create(bitmap);
encoder.Frames.Add(frame);

using (Stream stm = File.Create("filename.png"))
encoder.Save(stm);

However, when I try to implement this for LiveCharts2 with the following code, I'm not seeing any chart output as a PNG...

CartesianChart visual = new CartesianChart() {
    // Series = series,
    Height = 700,
    Width = 700,
    EasingFunction = null
};

var viewbox2 = new Viewbox();
viewbox2.Child = visual;
viewbox2.Measure(visual.RenderSize);
viewbox2.Arrange(new Rect(new System.Windows.Point(0, 0), visual.RenderSize));
visual.CoreChart.Update(new LiveChartsCore.Kernel.ChartUpdateParams() { IsAutomaticUpdate = false, Throttling = false });
viewbox2.UpdateLayout();

var encoder2 = new PngBitmapEncoder();
RenderTargetBitmap bmp = new(700, 700, 96, 96, PixelFormats.Pbgra32);
bmp.Render(visual);
encoder2.Frames.Add(BitmapFrame.Create(bmp));

using (Stream stm = File.Create("filename.png"))
    encoder2.Save(stm);

Can anyone help fix this issue? Thanks in advance.

CodePudding user response:

Found the answer here: https://github.com/beto-rodriguez/LiveCharts2/discussions/725#discussioncomment-4030202

var skChart = new SKCartesianChart(chartControl) { Width = 900, Height = 600, };
skChart.SaveImage("CartesianImageFromControl.png");
  • Related