user934902 user934902 - 8 months ago 72
iOS Question

CALayer cricle 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, bascially taking a large circle (mask) and shrinking it.

@IBOutlet weak var myView: UIView!

override func viewDidLoad() {

override func viewDidAppear(_ animated: Bool) {


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

enter image description here

enter image description here

Answer Source

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.