【发布时间】:2017-09-12 08:05:20
【问题描述】:
我正在动态生成图表,然后将其保存到图像文件中(它不必显示在 UI 中。)这是我在 WPF 代码中的图表代码。
<chart:PieChart
Name="chart1"
Style="{StaticResource MinimalChartStyle}"
ChartTitle="Minimal Pie Chart"
ChartSubTitle="Chart with fixed width and height"
SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}" Height="Auto" Width="Auto" >
<chart:PieChart.Series>
<chart:ChartSeries
SeriesTitle="Errors"
DisplayMember="Category"
ValueMember="Number"
ItemsSource="{Binding Path=Errors}" />
</chart:PieChart.Series>
</chart:PieChart>
.cs 代码之类的。
public ObservableCollection<TestClass> Errors { get; private set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
Errors = new ObservableCollection<TestClass>();
Errors.Add(new TestClass() { Category = "Globalization", Number = 75 });
Errors.Add(new TestClass() { Category = "Features", Number = 2 });
Errors.Add(new TestClass() { Category = "ContentTypes", Number = 12 });
Errors.Add(new TestClass() { Category = "Correctness", Number = 83 });
Errors.Add(new TestClass() { Category = "Best Practices", Number = 29 });
}
而我正在尝试做的是一种类似下面的方法,它可以构建一个类似上面的图表,然后将其保存到文件中以供进一步参考。
public bool buildChart() {
ClusteredBarChart newchart = new ClusteredBarChart();
//newchart.ActualWidth = 500; inaccessible
//newchart.ActualHeight = 400;
// T.B.D
...
...
newchart.DataContext = Errors;
saveTheChartToFile(newchart);
return true;
}
public bool saveTheChartToFile(ChartBase view)
{
Size size = new Size(view.ActualWidth, view.ActualHeight);
if (size.IsEmpty)
return false;
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);
BitmapEncoder encoder = new JpegBitmapEncoder();
MemoryStream file = new MemoryStream();
encoder.Frames.Add(BitmapFrame.Create(result));
encoder.Save(file);
System.IO.File.WriteAllBytes("d:\\ppp.jpeg", file.ToArray());
return true;
}
您似乎必须在使用之前在 XAML 中显式创建具有特定宽度和高度等的静态图表并将其导出到文件。有人可以帮忙吗?
【问题讨论】:
标签: c# .net wpf winforms charts