user934902
user934902

Reputation: 1204

CALayer circle mask animation incorrect behaviour + Swift

I have been trying to do this animation for a couple of days now. I am trying to animate the size of my mask, basically taking a large circle (mask) and shrinking it.

@IBOutlet weak var myView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        animateMask()
    }

    func presentMaskScreenWithAnimation () {

        //Setup Mask Layer
        let bounds = myView.bounds
        let maskLayer = CAShapeLayer()
        maskLayer.frame = bounds
        maskLayer.fillColor = UIColor.brown.cgColor

        //CropCircle Out of mask Layer
        let initialCircle = CGRect(x: 10, y: 10, width: 300, height: 300)
        let path = UIBezierPath(roundedRect: initialCircle, cornerRadius: initialCircle.size.width/2)

        path.append(UIBezierPath(rect: bounds))
        maskLayer.path = path.cgPath
        maskLayer.fillRule = kCAFillRuleEvenOdd

        myView.layer.mask = maskLayer

        //Define new circle path
        let circlePath2 = CGRect(x: 50, y: 50, width: 100, height: 100)
        let path2 = UIBezierPath(roundedRect: circlePath2, cornerRadius: circlePath2.size.width/2)


        //Create animation
        let anim = CABasicAnimation(keyPath: "path")



            anim.fromValue = path.cgPath
            anim.toValue = path2.cgPath
            anim.duration = 3.0
            anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)

            maskLayer.add(anim, forKey: nil)
    }

This code sets up the mask and begins to animate it however it inverts the entire maskLayer, I am trying to just animate the path of the circle, Large -> Small

Start enter image description here

Finished enter image description here

Upvotes: 1

Views: 821

Answers (1)

Eric Qian
Eric Qian

Reputation: 2256

Add path2.append(UIBezierPath(rect: bounds)) after let path2 = UIBezierPath(roundedRect: circlePath2, cornerRadius: circlePath2.size.width/2). Also do not forget to do maskLayer.path = path2.cgPath at the end, if you want the shrinking mask stays after animation.

Upvotes: 2

Related Questions