Visifire是一款用于WPF和Silverlight下的图表控件,支持多种常用的图表类型和图表功能,无论是在WPF还是silverlight下都可以帮助开发人员快速创建强大的数据可视化应用,这篇文章主要介绍如何使用Visifire图表导出为图片格式,具体参考下面的代码:
public Window1()
{
InitializeComponent();
// Call function to create chart
CreateChart();
}
// Chart variable
Chart chart;
private void CreateChart()
{
// Create a Chart
chart = new Chart();
// Set Chart size
chart.Width = 500;
chart.Height = 300;
// Initialize Random class
Random rand = new Random();
// Create DataSeries
DataSeries dataSeries = new DataSeries();
for (Int32 i = 0; i < 5; i++)
{
// Create DataPoint
DataPoint dataPoint = new DataPoint();
// Set DataPoint property
dataPoint.YValue = rand.Next(10, 100);
// Add DataPoint to DataPoints collection of DataSeries
dataSeries.DataPoints.Add(dataPoint);
}
// Add DataSeries to Series collection of Chart
chart.Series.Add(dataSeries);
// Add Chart to LayoutRoot
LayoutRoot.Children.Add(chart);
// Attach event to Chart
chart.MouseLeftButtonDown += new MouseButtonEventHandler(chart_MouseLeftButtonDown);
}
public void ExportToPng(Uri path, Visifire.Charts.Chart surface)
{
if (path == null) return;
// Save current canvas transform
Transform transform = surface.LayoutTransform;
// reset current transform (in case it is scaled or rotated)
surface.LayoutTransform = null;
// Create a render bitmap and push the surface to it
RenderTargetBitmap renderBitmap =
new RenderTargetBitmap(
(int)surface.Width,
(int)surface.Height,
96d,
96d,
PixelFormats.Pbgra32);
renderBitmap.Render(surface);
// Create a file stream for saving image
using (FileStream outStream = new FileStream(path.LocalPath, FileMode.Create))
{
// Use png encoder for our data
PngBitmapEncoder encoder = new PngBitmapEncoder();
// push the rendered bitmap to it
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
// save the data to the stream
encoder.Save(outStream);
}
// Restore previously saved layout
surface.LayoutTransform = transform;
}
void chart_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
ExportToPng(new Uri("d:/Visifire.png"), chart);
}