Animate a bezier path drawn in drawRect() Swift

后端 未结 2 1608
刺人心
刺人心 2020-12-25 14:49

I have this shape that i draw in drawRect()

var rectanglePath = UIBezierPath()

override func drawRect(rect: CGRect) {
    rectanglePath = UIBez         


        
2条回答
  •  庸人自扰
    2020-12-25 15:27

    To animate CGPath you cannot use UIView.animation methods. I created custom UIView subclass to show you how can you animate CGPaths shape, please refer to the comments and amend it for your requirements:

    class MyView: UIView {
    
    let shapeLayer = CAShapeLayer()
    let maskLayer = CAShapeLayer()
    var rectanglePath = UIBezierPath()
    
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
    
        backgroundColor = UIColor.clear
    
        // initial shape of the view
        rectanglePath = UIBezierPath(rect: bounds)
    
        // Create initial shape of the view
        shapeLayer.path = rectanglePath.cgPath
        shapeLayer.strokeColor = UIColor.black.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        layer.addSublayer(shapeLayer)
    
        //mask layer
        maskLayer.path = shapeLayer.path
        maskLayer.position =  shapeLayer.position
        layer.mask = maskLayer
    }
    
    func prepareForEditing(editing:Bool){
    
        let animation = CABasicAnimation(keyPath: "path")
        animation.duration = 2
    
        // Your new shape here
        animation.toValue = UIBezierPath(ovalIn: bounds).cgPath
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
    
        // The next two line preserves the final shape of animation,
        // if you remove it the shape will return to the original shape after the animation finished
        animation.fillMode = kCAFillModeForwards
        animation.isRemovedOnCompletion = false
    
        shapeLayer.add(animation, forKey: nil)
        maskLayer.add(animation, forKey: nil)
      }
    }
    

提交回复
热议问题