使用 UIBezierPath 和 iOS 绘制矩形填充圆圈动画

Filling circle animation with UIBezierPath and iOS draw rect

我在 github 上有这个:https://github.com/evertoncunha/EPCSpinnerView

它做这个动画:

动画中存在一个小故障,当圆正在填充并且视图正在调整大小时,我不想修复它。

这个问题是因为我通过设置图层角来填充圆,所以它看起来像一个圆,我随着动画的进展增加线宽,看起来像是从外向内填充。来自EPCDrawnIconSpinner.swift 文件:

let ovalPath = UIBezierPath()
ovalPath.addArc(withCenter: CGPoint(x: ovalRect.midX, y: ovalRect.midY),
                radius: ovalRect.width / 2,
                startAngle: start * CGFloat.pi/180,
                endAngle: end * CGFloat.pi/180, clockwise: true)
layer.cornerRadius = rect.size.height/2
ovalPath.lineWidth = 14 + ((frame.size.width) * progress)

有没有更好的方法可以在不执行图层 cornerRadius 的情况下实现此动画?如果我只能画这个

我可以想到两种方法来摆脱使用 cornerRadius:

  1. 使用蒙版圆角,使用形状图层填充

您可以创建一个 CAShapeLayer 实心圆,并将框架设置为视图的边界,然后将其分配给图层的 mask 属性。您可以在设置视图大小的动画时设置此遮罩的大小。其次,稍后您需要创建一个额外的形状(可能类似于您旋转的圆圈),并在此层上制作线宽动画。遮罩将确保线条不会向外生长,而只会向内生长。

  1. 动画填充形状的线宽半径

您将需要创建一个与第一个选项中描述的相似的圆形图层,但您不仅需要为线宽设置动画,还需要为半径设置动画。例如:假设您的视图大小为 40x40。当然,在填充动画开始时,形状图层也需要为 40x40。然后将线宽设置为 20pts,并将圆的半径设置为 20pts 到 10pts。一个半径为10pts,线宽为20pts的圆,看起来就是一个半径为20pts的实心圆

希望对您有所帮助。

我最终得到以下解决方案:

fileprivate func drawPathCompleted(_ ovalRect: CGRect) {

     var size: CGFloat = ovalRect.size.width

     var current = size*(1-progress)

     var pos: CGFloat = lineWidth/2

     while size > current {
       let ovalPath = UIBezierPath(ovalIn: CGRect(x: pos, y: pos, width: size, height: size))
       ovalPath.lineCapStyle = .round
       ovalPath.lineWidth = lineWidth
       ovalPath.stroke()
       let decr = lineWidth/2
       size -= decr
       pos += decr/2
     }
}

在这次提交中,第 243 行: https://github.com/evertoncunha/EPCSpinnerView/commit/87d968846d92aa97e85ff4c58b6664ad7b03f00b#diff-8dc22814328ed859a00acfcf2909854bR242