除了仪表盘控件比较常用外,还有图表也经常使用,同样网上也有非常强大的图表控件,有收费的(DEVexpress),也有免费的。但我们平时在使用时,只想简单地绘一个图,控件库里面的许多功能我们都用不到,没必要使用那么功能丰富的控件,以提高程序运行的效率和减小程序的占用空间。同时,我们自己如果能够绘制图表出来,对于程序的移植,也非常方便。对于大部分平台,相信设计方法是不会变的。废话少讲,直接上图看效果,如果觉得还不错,可以支持一下,继续往下看。源码下载地址:https://github.com/Endless-Coding/MyGauge/blob/master/CustomControl.zip
1、图表整体设计
简单来看一个图表的组成,一般由4个部分组成,坐标轴,刻度和刻度值,绘图区域(添加数据点和绘制曲线)。后面如果要做到数据动态显示,还要花一点点功夫,不过也是很容易的,耐心研究,不会比高等数学难。
2、坐标轴绘制
先作出两根垂直的直线出来,为x轴和y轴,XAML代码如下。2,3行代码即为两个数轴。4~23行,是作出两个小三角形,以形成箭头的形状。
1 <Canvas Margin="5"> 2 <Line x:Name="x_axis" Stroke="Black" StrokeThickness="3" X1="40" Y1="280" X2="480" Y2="280" StrokeStartLineCap="Round"/> 3 <Line x:Name="y_axis" Stroke="Black" StrokeThickness="3" X1="40" Y1="280" X2="40" Y2="30" StrokeStartLineCap="Round"/> 4 <Path x:Name="x_axisArrow" Fill="Black"> 5 <Path.Data> 6 <PathGeometry> 7 <PathFigure StartPoint="480,276" IsClosed="True"> 8 <LineSegment Point="480,284"/> 9 <LineSegment Point="490,280"/> 10 </PathFigure> 11 </PathGeometry> 12 </Path.Data> 13 </Path> 14 <Path x:Name="y_axisArrow" Fill="Black"> 15 <Path.Data> 16 <PathGeometry> 17 <PathFigure StartPoint="36,30" IsClosed="True"> 18 <LineSegment Point="44,30"/> 19 <LineSegment Point="40,20"/> 20 </PathFigure> 21 </PathGeometry> 22 </Path.Data> 23 </Path> 24 </Canvas>
C#作出两个小箭头的后台代码如下:
1 /// <summary> 2 /// 作出箭头 3 /// </summary> 4 private void DrawArrow() 5 { 6 Path x_axisArrow = new Path();//x轴箭头 7 Path y_axisArrow = new Path();//y轴箭头 8 9 x_axisArrow.Fill = new SolidColorBrush(Color.FromRgb(0xff, 0, 0)); 10 y_axisArrow.Fill = new SolidColorBrush(Color.FromRgb(0xff, 0, 0)); 11 12 PathFigure x_axisFigure = new PathFigure(); 13 x_axisFigure.IsClosed = true; 14 x_axisFigure.StartPoint = new Point(480, 276); //路径的起点 15 x_axisFigure.Segments.Add(new LineSegment(new Point(480, 284), false)); //第2个点 16 x_axisFigure.Segments.Add(new LineSegment(new Point(490, 280), false)); //第3个点 17 18 PathFigure y_axisFigure = new PathFigure(); 19 y_axisFigure.IsClosed = true; 20 y_axisFigure.StartPoint = new Point(36, 30); //路径的起点 21 y_axisFigure.Segments.Add(new LineSegment(new Point(44, 30), false)); //第2个点 22 y_axisFigure.Segments.Add(new LineSegment(new Point(40, 20), false)); //第3个点 23 24 PathGeometry x_axisGeometry = new PathGeometry(); 25 PathGeometry y_axisGeometry = new PathGeometry(); 26 27 x_axisGeometry.Figures.Add(x_axisFigure); 28 y_axisGeometry.Figures.Add(y_axisFigure); 29 30 x_axisArrow.Data = x_axisGeometry; 31 y_axisArrow.Data = y_axisGeometry; 32 33 this.chartCanvas.Children.Add(x_axisArrow); 34 this.chartCanvas.Children.Add(y_axisArrow); 35 }