如何使用 angular 渐变制作圆形 UIView

How to make a circular UIView with an angular gradient

我需要做一个像

这样的视图

它是一个圆形线段,必须具有 angular 渐变和圆角。

我需要知道如何制作 angular 渐变,如图所示。

我使用 UIBezierPath class 做了类似的事情。特别是 addArcWithCenter 函数:

let line = UIBezierPath()
line.addArcWithCenter(centerPoint, radius: curveRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
color.setStroke()
line.stroke()

centerPoint, curveRadius, startAngle, endAngle 都提前设置好了

Color 是一个 UIColor,用于给线条颜色。

下面是我的做法。

  1. 创建一个 CALayer 来为加载程序绘制 'background'。不幸的是,在 Core Animation 或 Core Graphics 中没有创建角度渐变的内置方法。您要么必须使用带有 CAGradientLayer 的线性渐变,要么查看 AngleGradientLayer.

  2. 创建一个 CAShapeLayer 来定义您的圆弧。然后,您将要使用 UIBezierPath+bezierPathWithArcCenter:radius:startAngle:endAngle:clockwise: method. You can then assign this path to the CAShapeLayer's path 属性.

  3. 创建弧形路径
  4. 然后您将要配置 CAShapeLayer 的描边。您需要将 lineWidth to the width of your stroke and set the lineCap 属性 设置为 kCALineCapRound.

  5. 将您的 CAShapeLayer 分配给背景 CALayermask 属性。这会将加载程序的 'background' 屏蔽到描边路径。

  6. 添加你的背景CALayeras a sublayer to a UIView's layer. (Or create a subclass of UIView and CALayer and return your custom layer class in the view's +layerClass方法)

  7. 使用 CAShapeLayerstrokeStart and strokeEnd 属性的 CABasicAnimation 制作动画。