如何在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  欢迎加入

posted @ 2010-04-07 09:53  Jarrey  阅读(5430)  评论(2编辑  收藏  举报