推荐一个支持多平台、多框架的.Net绘图库。
01 项目简介
OxyPlot是一个基于.NET开发的、跨平台的绘图库,可用于多种平台和框架,如WPF、Windows 8、Windows Phone、Windows Phone Silverlight、Windows Forms、Silverlight、GTK#、Xwt、Xamarin.iOS、Xamarin.Android、Xamarin.Forms和Xamarin.Mac等。它提供了丰富的绘图功能,可以用于创建各种类型的图表,如折线图、柱状图、饼图、散点图等。
02 使用方法
1、安装依赖库
Install-Package OxyPlot.Core
Install-Package OxyPlot.Core.Drawing
2、示例代码
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Core.Drawing;
using OxyPlot.Series;
class Program
{
static void Main(string[] args)
{
var outputToFile = "test-oxyplot-static-export-file.png";
var outputExportStreamOOP = "test-oxyplot-ExportToStream.png";
var outputExportFileOOP = "test-oxyplot-ExportToFile.png";
var width = 1024;
var height = 768;
var background = OxyColors.LightGray;
var resolution = 96d;
var model = BuildPlotModel();
// 使用静态方法导出到文件
PngExporter.Export(model, outputToFile, width, height, resolution);
// 使用实例方法导出
using (var stream = new MemoryStream())
{
var pngExporter = new PngExporter { Width = width, Height = height, Resolution = resolution };
pngExporter.Export(model, stream);
System.IO.File.WriteAllBytes(outputExportStreamOOP, stream.ToArray());
}
var pngExporter2 = new PngExporter { Width = width, Height = height, Resolution = resolution };
var bitmap = pngExporter2.ExportToBitmap(model);
bitmap.Save(outputExportFileOOP, System.Drawing.Imaging.ImageFormat.Png);
bitmap.Save(Path.ChangeExtension(outputExportFileOOP, ".gif"), System.Drawing.Imaging.ImageFormat.Gif);
}
private static IPlotModel BuildPlotModel()
{
var rand = new Random(21);
var model = new PlotModel { Title = "蛋糕类型受欢迎程度" };
var cakePopularity = Enumerable.Range(1, 5).Select(i => rand.NextDouble()).ToArray();
var sum = cakePopularity.Sum();
var barItems = cakePopularity.Select(cp => RandomBarItem(cp, sum)).ToArray();
var barSeries = new BarSeries
{
ItemsSource = barItems,
LabelPlacement = LabelPlacement.Base,
LabelFormatString = "{0:.00}%"
};
model.Series.Add(barSeries);
model.Axes.Add(new CategoryAxis
{
Position = AxisPosition.Left,
Key = "CakeAxis",
ItemsSource = new[]
{
"Apple cake",
"Baumkuchen",
"Bundt Cake",
"Chocolate cake",
"Carrot cake"
}
});
return model;
}
private static BarItem RandomBarItem(double cp, double sum)
=> new BarItem { Value = cp / sum * 100, Color = RandomColor() };
private static OxyColor RandomColor()
{
var r = new Random();
return OxyColor.FromRgb((byte)r.Next(255), (byte)r.Next(255), (byte)r.Next(255));
}
}
3、效果

03 部分绘图效果
1、折线图

2、柱状图

3、热图

4、饼图

5、三角函数

04 项目地址
https://github.com/oxyplot/oxyplot
更多开源项目: https://github.com/bianchenglequ/NetCodeTop
- End -
推荐阅读
Translumo:基于.NET开发的开源的屏幕实时翻译工具