如何在WPF Toolkit Chart基礎上實現步線圖(SetpLineChart)效果
WPF Toolkit 的Chart組件本身提供了很多統計圖表效果,但里面缺少了步線圖(StepLineChart)效果。在CodePlex中,有一個庫 Visifire 提供了步線圖效果,但我想在Toolkit基礎上實現一個輕量級的簡單的步線效果,畢竟實用簡單免費很重要。
不多說,開始研究Toolkit的源碼;在 System.Windows.Controls.DataVisualization.Charting.LineSeries 類中的 UpdateShapeFromPoints(IEnumerable<Point>points) 方法返回了圖表上最終繪制的各個坐標點,而這個方法是可以被重載的,所以我們就可以在子類中重載他改變最終輸出點的坐標的順序或者可以在原有的坐標點上插入新的點。
我們來研究下步線圖的特性結構;在步線圖中,當前點和下一點的連接線始終是有一個直角線的,經過觀察,我們可以在當前點和下一點之間插入一個點,使這個點的Y值等于當前點的Y值,這個點的X值等于下一點的X值,這樣將這三個點連接起來就繪出了一個直角效果,從而達到了步線圖效果,如下圖:

最后上代碼,我繼承了LineSeries類創建了一個新類StepLineSeries,并且重載了UpdateShapeFromPoints方法來重新排列和插入了坐標點,如下:
1 using System.Collections.ObjectModel;
2 using System.Windows.Controls.DataVisualization.Charting;
3 using System;
4 using System.Windows.Media;
5 using System.Windows;
6 using System.Collections.Generic;
7 using System.Linq;
8
9 namespace StepLineChart
10 {
11
12 public class StepLineSeries : LineSeries
13 {
14 /// <summary>
15 /// Gets the collection of points that make up the line.
16 /// </summary>
17 public PointCollection Points
18 {
19 get { return GetValue(PointsProperty) as PointCollection; }
20 private set { SetValue(PointsProperty, value); }
21 }
22
23 protected override void UpdateShapeFromPoints(IEnumerable<Point> points)
24 {
25 if (points.Any())
26 {
27 PointCollection pointCollection = new PointCollection();
28 foreach (Point point in points)
29 {
30 pointCollection.Add(point);
31 }
32 Points = CreateStepLineSeries(pointCollection);
33 }
34 else
35 {
36 Points = null;
37 }
38 }
39
40 /// <summary>
41 /// 根據已有的坐標點插入新的拐點
42 /// </summary>
43 /// <param name="points"></param>
44 /// <returns></returns>
45 private PointCollection CreateStepLineSeries(PointCollection points)
46 {
47 PointCollection returnPoints = new PointCollection();
48 for (int i = 0; i < points.Count; i++)
49 {
50 Point currentPoint = points[i];
51 returnPoints.Add(currentPoint);
52 if (i < points.Count - 1)
53 {
54 Point nextPoint = points[i + 1];
55 returnPoints.Add(new Point(nextPoint.X, currentPoint.Y));
56 }
57 }
58 return returnPoints;
59 }
60 }
61 }
62
最終效果圖:

示例下載:http://cid-51b2fdd068799d15.skydrive.live.com/self.aspx/.Public/StepLineChart.zip
WPF QQ交流群: 113404016 歡迎加入
浙公網安備 33010602011771號