在 Silverlight 中绘制扇形

/// <summary>
/// 获得扇形的 Path 对象。
/// </summary>
/// <param name="x">图形左上角的坐标之 x</param>
/// <param name="y">图形左上角的坐标之 y</param>
/// <param name="rotationAngle">扇形的角度。</param>
/// <param name="radius">扇形的半径大小,更改其值会影响扇形大小。</param>
/// <param name="angle">扇形张开的角度,支持0 - 360 度,使用弧度。</param>
/// <returns></returns>
public static Path GetSectorPath(double x, double y, double rotationAngle, double radius, double angle, Color col)
{
    // 对整圆的特殊处理
    if (angle > Math.PI * 1.9999)
        angle = Math.PI * 1.9999;

    var path = new Path
    {
        Fill = new SolidColorBrush(col),
        RenderTransformOrigin = new Point(radius, radius),
        Stretch = Stretch.None,
        UseLayoutRounding = false
    };

    //绘制起始直线
    var startLine = new LineSegment()
    {
        Point = new Point(radius * 2, radius)
    };
    //绘制弧线
    var arcLine = new ArcSegment()
    {
        IsLargeArc = angle > Math.PI ? true : false,
        Size = new Size(radius, radius),
        Point = new Point(radius * Math.Cos(angle) + radius, radius * Math.Sin(angle) + radius),
        SweepDirection = SweepDirection.Clockwise
    };
    //绘制结束直线
    var endLine = new LineSegment()
    {
        Point = new Point(radius, radius)
    };
    //把三条线段集合在一起。
    var segments = new PathSegmentCollection { startLine, arcLine, endLine };

    //为直线的Data赋值,由三段封闭的线段绘制成一个扇形
    path.Data = new PathGeometry()
    {
        Figures = new PathFigureCollection() { new PathFigure()
                                                    {
                                                        StartPoint = new Point(radius, radius),
                                                        Segments = segments
                                                    }}
    };

    //设置扇形对称轴偏转角度。
    path.RenderTransform = new CompositeTransform()
    {
        Rotation = rotationAngle,
        CenterX = radius, // 很重要,设置旋转中心。在 Path.RenderTransformOrigen 设置无效。
        CenterY = radius
    };

    path.SetValue(Canvas.LeftProperty, x);
    path.SetValue(Canvas.TopProperty, y);
    return path;
}

这段代码的主要思路如下:

  1. 使用 Path 对象,组合两条边和一个弧来形成扇形。
  2. 弧线和边均以 X 轴正方向为基准绘制。(一条边为与 X 轴正方向重合的边,其他线条以此为起点顺时针方向绘制)
  3. 绘制完成后,使用 PathRenderTransform 属性,将其旋转到合适的开始角度。
  4. 使用 SinCos 函数计算相关坐标。

本文版权遵循 CC BY-NC-SA 4.0发布,转载需附带本文链接。

当前页阅读量为: