我正在尝试在c#代码中创建一个WPF图表并将其保存到文件而不显示在屏幕上。这将在WCF服务中将数据发送到服务,创建映像并返回映像路径。在没有XAML的情况下在WPF中创建图像并显示
到目前为止,我已经得到了要保存到文件的图像,并且显示了Y轴上的数据,但图中的列未被绘制。
有谁知道为什么在图表上的列没有绘制...这里是我的代码:
公共无效的DoWork(){ VAR = newThread新的Thread(创建图像); newThread.SetApartmentState(ApartmentState.STA); newThread.Start(); }
public void CreateImage()
{
var grid = new Grid {Width = 800, Height = 600, Background = new SolidColorBrush(Colors.LightBlue)};
var chart = new Chart();
grid.Children.Add(chart);
var renderTarget = new RenderTargetBitmap((int)grid.Width, (int)grid.Height, 96d, 96d, PixelFormats.Default);
var barSeries = new BarSeries
{
Title = "Fruit in Cupboard",
ItemsSource = new[]
{
new KeyValuePair<string, int>("Oranges", 18),
new KeyValuePair<string, int>("Apples", 15),
new KeyValuePair<string, int>("Melons", 2),
new KeyValuePair<string, int>("Pineapples", 4),
new KeyValuePair<string, int>("Plums", 25)
},
IndependentValueBinding = new Binding("Key"),
DependentValueBinding = new Binding("Value")
};
chart.Series.Add(barSeries);
grid.Measure(new Size(grid.Width, grid.Height));
grid.Arrange(new Rect(new Size(grid.Width, grid.Height)));
grid.UpdateLayout();
renderTarget.Render(grid);
var png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(renderTarget));
using (Stream stm = File.Create(string.Format(@"C:/Images/{0}.png", Guid.NewGuid())))
{
png.Save(stm);
}
}
我认为这是一个事实,当条形图数据被添加到图表时,正常的过程是让图表动画化这些列作为淡入......所以我正在拍摄图表的快照在动画发生之前。 – 2010-09-07 10:32:50