wpfchartssyncfusion

Unable to generate graphics in background (without displaying UI)


I am trying to generate syncfusion charts in the background of a screen opening and thus be able to save them in PNG.

Each chart is in a UserControl with a custom legend (not the synfusion one). So I have to generate this UserControl with the chart (SfCharts) inside and its associated legend and then save it in PNG.

I used these instructions in particular:

private void GenerateGraphImage(object graphiqueBar, GraphiqueSynthese graphique)
{
    // binded property containing with some chart's datas
    GraphiqueSyntheseAAfficher = graphique;

    // try to force render user control
    if (graphiqueBar is UserControl userControl)
    {             
        userControl.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
        userControl.Arrange(new Rect(userControl.DesiredSize));
        userControl.UpdateLayout();

        // get image
        var image = ScreenshotHelper.GetImage(userControl);

        // save as png
        SaveImage(image, graphique.GraphiqueName);
    }
}

public static RenderTargetBitmap GetImage(UserControl view)
{
    Size size = new Size(view.ActualWidth, view.ActualHeight);
    if (size.IsEmpty)
        return null;

    RenderTargetBitmap result = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32);

    DrawingVisual drawingvisual = new DrawingVisual();
    using (DrawingContext context = drawingvisual.RenderOpen())
    {
        context.DrawRectangle(new VisualBrush(view), null, new Rect(new Point(), size));
        context.Close();
    }

    result.Render(drawingvisual);
    return result;
}

I can see the UserControl built in memory (by hovering the mouse over the "userControl" variable) after UpdateLayout(), it has a size (ActualWidth and ActualHeight are not 0), the control that builds the legend is correctly built (with the bound properties). On the other hand, the chart is always empty: no data or drawing (bar or curve) appears...

userControl variable filled

I can't figure out why?

For additional information:

Do you have a solution or an idea of ​​this problem?

An example of the result :

enter image description here


Solution

  • If someone looking for the solution.

    You need to wait the chart rendered its elements (like a bar).

    I added a Thread.Sleep(1000) after the forced rendered and before to save the visual as png. And it work !

     chart.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
     chart.Arrange(new Rect(userControl.DesiredSize));
     Thread.Sleep(900);
     // and save as png
    

    Many thanks to Gerry in comments !