上一小节讲解了动态生成折线图和区域图,对于简单的图形这样通过C#代码来生成的方式是很方便的,但是当我们的图表要实现更加复杂的逻辑的时候,这种动态生成的方式就显得力不从心了,那就需要利用控件封装的方式来实现更加强大的图表控件功能。这一小节将来讲解怎样去用封装控件的方式去实现图表,用一个饼图控件作为例子进行分析讲解。
饼图其实就是把一个圆形分成若干块,每一块代表着一个类别的数据,可以把这每一块的图形看作是饼图片形形状。要实现一个饼图控件,首先需要做的就是要实现饼图片形形状,在第4章里面讲解了实现如何实现自定义的形状,饼图片形形状也可以通过这种方式来实现。饼图片形形状有一些重要的属性,如饼图半径Radius,内圆半径InnerRadius,旋转角度RotationAngle,片形角度WedgeAngle,点innerArcStartPoint,点innerArcEndPoint,点outerArcStartPoint和点outerArcEndPoint等,这些属性的含义如图13.5所示。要绘制出这个饼图片形形状需要计算出4个点的坐标(点innerArcStartPoint,点innerArcEndPoint,点outerArcStartPoint和点outerArcEndPoint),这4的点的坐标需要通过半径和角度相关的属性计算出来。计算出这4个点的坐标的坐标之后,然后通过这4个点创建一个Path图形,这个Path图形由两条直线和两条弧线组成,形成了一个饼图片形形状。通过这种方式不仅仅把这个饼图片形形状创建好了,连这个图形在整个饼图的位置也设置好了。代码如下所示。
PiePiece.cs文件代码:自定义的饼图片形形状
------------------------------------------------------------------------------------------------------------------
using System;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;
namespace PieChartDemo
{
/// <summary>
/// 自定义的饼图片形形状
/// </summary>
class PiePiece : Path
{
#region 依赖属性
// 注册半径属性
public static readonly DependencyProperty RadiusProperty =
DependencyProperty.Register("RadiusProperty", typeof(double), typeof(PiePiece),
new PropertyMetadata(0.0));
// 饼图半径
public double Radius
{
get { return (double)GetValue(RadiusProperty); }
set { SetValue(RadiusProperty, value); }
}
// 注册饼图片形点击后推出的距离
public static readonly DependencyProperty PushOutProperty =
DependencyProperty.Register("PushOutProperty", typeof(double), typeof(PiePiece),
new PropertyMetadata(0.0));
// 距离饼图中心的距离
public double PushOut
{
get { return (double)GetValue(PushOutProperty); }
set { SetValue(PushOutProperty, value); }
}
// 注册饼图内圆半径属性
public static readonly DependencyProperty InnerRadiusProperty =
DependencyProperty.Register("InnerRadiusProperty", typeof(double), typeof(PiePiece),
new PropertyMetadata(0.0));
// 饼图内圆半径
public double InnerRadius
{
get { return (double)GetValue(InnerRadiusProperty); }
set { SetValue(InnerRadiusProperty, value); }
}
// 注册饼图片形的角度属性
public static readonly DependencyProperty WedgeAngleProperty =
DependencyProperty.Register("WedgeAngleProperty", typeof(double), typeof(PiePiece),
new PropertyMetadata(0.0));
// 饼图片形的角度
public double WedgeAngle
{
get { return (double)GetValue(WedgeAngleProperty); }
set
{
SetValue(WedgeAngleProperty, value);
this.Percentage = (value / 360.0);
}
}
// 注册饼图片形旋转角度的属性
public static readonly DependencyProperty RotationAngleProperty =
DependencyProperty.Register("RotationAngleProperty", typeof(double), typeof(PiePiece),
new PropertyMetadata(0.0));
// 旋转的角度
public double RotationAngle
{
get { return (double)GetValue(RotationAngleProperty); }
set { SetValue(RotationAngleProperty, value); }
}
// 注册中心点的X坐标属性
public static readonly DependencyProperty CentreXProperty =
DependencyProperty.Register("CentreXProperty", typeof(double), typeof(PiePie