我有一个小问题。我想将我的图表导出到图像。我知道使用 beto-rodriguez 给出的代码(这里)是可能的。
但是我有一个问题,我无法通过在屏幕上显示它来获得我可以拥有的东西。见上图。在右下角,我将图像保存在 png 中。在图像的左侧,我有一个图表,所有参数都显示在我想要的位置。
您是否知道保存的图像中是否可以有相同的图表(在左侧)?实际上,我使用线程自动捕获(复制/粘贴)图像。
你知道我必须设置哪些参数才能获得正确的图像吗?
提前致谢。问候。
************************************ 修改后
抱歉我的回复晚了。我试试你说的,但不幸的是我做不到我想要的。我将解释我的工作:我有一个类“MakeReport”,它可以调用另一个类“GraphMaker”:
MyGraph = new GraphMaker();
MyGraph = GiveAGraph(MyGraph);
“MakeReport”类将使用子程序“GiveAGraph()”完成带有一些值的图表:
GraphData.SeriesCollection.Add(new RowSeries
{
Title = Criteria,
Values = DataValues,
ScalesYAt = Index,
DataLabels = true
});
“GiveAGRaph()”结束。
现在我准备好显示一个图表,我想用它来制作图像并用于测试(和调试)我显示它:
// Chart to Image
MyGraph.GiveMeAnImageFromChart(); <-- to make a picture with the chart
// Show the graph
MyGraph.Show(); <-- for debug and test, i display it.
使用“MyGraph.GiveAnImageFromChart()”,我没有与“MyGraph.Show()”相同的结果。图片(另存为 png)与显示的图表不同。
“GraphMaker”类中包含的子程序“GiveAnImageFromChart”是:
public void GiveMeAnImageFromChart()
{
var viewbox = new Viewbox();
myChart.Background = Brushes.White;
myChart.DataContext = this;
// myChart il faut tout mettre en paramètres
viewbox.Child = myChart;
viewbox.Measure(myChart.RenderSize);
viewbox.Arrange(new Rect(new Point(0, 0), myChart.RenderSize));
myChart.Update(true, true); //force chart redraw
viewbox.UpdateLayout();
SaveToPng(myChart, "chart.png");
//png file was created at the root directory.
}
“myChart”变量是公开的。使用的“SaveToPng”程序来自您的示例(此处)。
为了保存图片,我尝试使用以下方法:
public System.Drawing.Bitmap ControlToImage(Visual target, double dpiX, double dpiY)
{
if (target == null)
{
return null;
}
// render control content
Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
Console.WriteLine("Bounds width = " + bounds.Width + " et bounds height = " + bounds.Height);
RenderTargetBitmap rtb = new RenderTargetBitmap((int)(bounds.Width * dpiX / 96.0),
(int)(bounds.Height * dpiY / 96.0),
dpiX,
dpiY,
PixelFormats.Pbgra32);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(target);
ctx.DrawRectangle(vb, null, new Rect(new System.Windows.Point(), bounds.Size));
}
rtb.Render(dv);
//convert image format
MemoryStream stream = new MemoryStream();
BitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(rtb));
encoder.Save(stream);
return new System.Drawing.Bitmap(stream);
}
和 :
Bitmap ImageChart = MyGraph.ControlToImage(MyGraph, MyGraph.Width, MyGraph.Height);
使用这种方法,我有一个错误,因为“bounds.Width”和“bounds.Height”等于-8。最后,我没有要转换的图表。
我想我在“ControlImage”中给出了错误的“视觉目标”,我错过了一些东西,但我不知道是什么。如果您需要更多信息,请询问我。在此先感谢您的帮助。
PS:对不起我的英语。不要犹豫纠正我。