如何在Swift 4中绘制半(半)圆并将其动画化为特定角度?

时间:2018-08-14 05:27:55

标签: ios swift

 let slayer = CAShapeLayer()
 let center = CGPoint(x: (bounds.width / 2) + 4, y: bounds.height - 8)
 let radius: CGFloat = bounds.height - 16
 let startAngle: CGFloat = 4 * .pi / 4
 let endAngle: CGFloat = 0.0
 slayer.path = UIBezierPath(arcCenter: center,
                               radius: radius,
                               startAngle: startAngle,
                               endAngle: endAngle,
                               clockwise: true).cgPath
 slayer.lineWidth = 15.0
 slayer.lineCap = kCALineCapRound
 slayer.strokeColor = UIColor.blue.cgColor
 slayer.fillColor = UIColor.clear.cgColor
 self.layer.addSublayer(slayer)

请查看下图。要求是带有动画的圆,直到特定角度。

enter image description here

2 个答案:

答案 0 :(得分:0)

使用2个CA Shape Layer对象,一个用于灰度(不带动画),另一个用于蓝色(带动画)。

 func addCircle(color: UIColor) -> CAShapeLayer
    {
        let centre = CGPoint(x: view.bounds.size.width/2, y: view.bounds.size.height/2)
        let beizerPath = UIBezierPath(arcCenter: centre, radius: 30.0, startAngle: .pi, endAngle: 2.0 * .pi, clockwise: true)
        let circleLayer = CAShapeLayer()
        circleLayer.path = beizerPath.cgPath
        circleLayer.fillColor = color.cgColor
        circleLayer.strokeEnd = 1.0

        captureButton.layer.addSublayer(circleLayer)
        return circleLayer
    }

    func animateButton()
    {
        blueLayer = addCircle(color: .blue)
        blueLayer!.strokeEnd = 0.0

        let animation = CABasicAnimation(keyPath: "strokeEnd")
        animation.duration = 60.0
        animation.fromValue = 0.0
        animation.toValue = 1.0
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
        blueLayer!.strokeEnd = 1.0
        blueLayer!.add(animation, forKey: nil)
    }

答案 1 :(得分:0)

您可以通过在圆上添加另一层并使它的笔触末端属性动画化来对圆进行动画处理。

  func animate()
    {
      let slayer = CAShapeLayer()
      let center = CGPoint(x: (bounds.width / 2) + 4, y: bounds.height - 8)
      let radius: CGFloat = bounds.height - 16
      let startAngle: CGFloat = 4 * .pi / 4
      let endAngle: CGFloat = 0.0
      slayer.path = UIBezierPath(arcCenter: center,
                               radius: radius,
                               startAngle: startAngle,
                               endAngle: endAngle,
                               clockwise: true).cgPath
      slayer.lineWidth = 15.0
      slayer.lineCap = kCALineCapRound
      slayer.strokeColor = UIColor.blue.cgColor
      slayer.fillColor = UIColor.clear.cgColor
      self.layer.addSublayer(slayer)
      slayer.strokeEnd = 0.0

      let animation = CABasicAnimation(keyPath: "strokeEnd")
      animation.duration = 60.0 .  //Customize the time of your animation here.
      animation.fromValue = 0.0
      animation.toValue = 1.0
      animation.timingFunction = CAMediaTimingFunction(name: 
      kCAMediaTimingFunctionLinear)
      slayer.strokeEnd = 1.0
      slayer.add(animation, forKey: nil)
    }