我正在嘗試在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