最近在WPF中做一个需要实现统计的功能,其中需要用到统计图,之前也没有接触过,度娘上大多都是各种收费或者免费的第三方控件,不想用第三方控件那就自己画一个吧。
在园子还找到一篇文章,思路来自这篇文章,文章链接:http://www.cnblogs.com/endlesscoding/p/6670432.html
不过根据我的需求,数据每次都在变化,所以都只能从后台绑定,先来看一下完成后的效果吧
可以看到,数据源是一年内一到十二月的金额,所以X轴是固定的,而Y轴标尺是根据数据源的最大值向上取100。再来计算每个标尺该显示的数值。
数据点的显示,也是根据提供数据的比例,来计算出像素值的
从头开始吧,先来说xaml,xaml中需要一个Canvas控件,之后所有的图形就是画在这里面
不会用Canvas的话可以先学习下官方文档:https://msdn.microsoft.com/zh-cn/library/system.windows.controls.canvas(v=vs.110).aspx
1 <Grid Height="400" Width="645">
2 <Grid.ColumnDefinitions>
3 <ColumnDefinition Width="150" />
4 <ColumnDefinition Width="330"/>
5 <ColumnDefinition Width="*"/>
6 </Grid.ColumnDefinitions>
7 <Grid.RowDefinitions>
8 <RowDefinition Height="25" />
9 <RowDefinition />
10 </Grid.RowDefinitions>
11 <j:JLabel Label="企业账号:" Grid.Column="0" Grid.Row="0">
12 <TextBlock Text="{Binding Userid}" HorizontalAlignment="Left" Foreground="Red"/>
13 </j:JLabel>
14 <j:JLabel Label="企业名称:" Grid.Column="1" Grid.Row="0">
15 <TextBlock Text="{Binding Username}" HorizontalAlignment="Left" Foreground="Red"/>
16 </j:JLabel>
17 <j:JLabel Label="总金额(元):" Grid.Column="2" Grid.Row="0">
18 <TextBlock Text="{Binding Pay_Total}" HorizontalAlignment="Left" Foreground="Red"/>
19 </j:JLabel>
20 <Canvas x:Name="chartCanvas" Margin="5" Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="4">
21 </Canvas>
22 </Grid>
先来画横纵坐标和箭头吧,x1,y1,x2,y2这四个参数是Line在Canvas中的起点终点位置像素值
同样,Line类官方文档:https://msdn.microsoft.com/zh-cn/library/system.windows.shapes.line(v=vs.110).aspx
1 /// <summary>
2 /// 生成横纵坐标及箭头
3 /// </summary>
4 private void DrawArrow()
5 {
6 Line x_axis = new Line();//x轴
7 Line y_axis = new Line();//y轴
8 x_axis.Stroke = System.Windows.Media.Brushes.Black;
9 y_axis.Stroke = System.Windows.Media.Brushes.Black;
10 x_axis.StrokeThickness = 3;
11 y_axis.StrokeThickness = 3;
12 x_axis.X1 = 40;
13 x_axis.Y1 = 320;
14 x_axis.X2 = 600;
15 x_axis.Y2 = 320;
16 y_axis.X1 = 40;
17 y_axis.Y1 = 320;
18 y_axis.X2 = 40;
19 y_axis.Y2 = 30;
20 this.chartCanvas.Children.Add(x_axis);
21 this.chartCanvas.Children.Add(y_axis);
22
23 Line y_scale1 = new Line(); //坐标原点直角
24 y_scale1.Stroke = System.Windows.Media.Brushes.Black;
25 y_scale1.StrokeThickness =1;
26 y_scale1.X1 = 40;
27 y_scale1.Y1 = 310;
28 y_scale1.X2 = 44;
29 y_scale1.Y2 = 310;
30 y_scale1.StrokeStartLineCap = PenLineCap.Triangle;
31 this.chartCanvas.Children.Add(y_scale1);
32
33 Path x_axisArrow = new Path();//x轴箭头
34 Path y_axisArrow = new Path();//y轴箭头
35 x_axisArrow.Fill = new SolidColorBrush(Color.FromRgb(0, 0, 0));
36 y_axisArrow.Fill = new SolidColorBrush(Color.FromRgb(0, 0, 0));
37 PathFigure x_axisFigure = new PathFigure();
38 x_axisFigure.IsClosed = true;
39 x_axisFigure.StartPoint = new Point(600, 316); //路径的起点
40 x_axisFigu