我正致力于动态生成图表,然后将其保存到图像文件(不必在 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 中显式创建具有特定宽度和高度等的静态图表并将其导出到文件中。有人可以帮忙吗?
在渲染之前尝试测量和安排控件:
public bool saveTheChartToFile(ChartBase view)
{
Size size = new Size(100, 100);
RenderTargetBitmap result = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32);
view.Measure(size);
view.Arrange(new Rect(size));
result.Render(view);
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(result));
using (Stream stm = File.Create("test.jpg"))
{
encoder.Save(stm);
}
return true;
}
我是一名优秀的程序员,十分优秀!