0

I'm looking to animate a CAShapelayer from the center of a view. My animation is working fine, but it's animating (expanding) from (0,0) as opposed to the center of the shape. I'm calling this in ViewDidAppear. Here's my code:

    introAnimationImageView.image = UIImage(named:"mainBGblue")
    self.view.addSubview(introAnimationImageView)

    introAnimationImageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
    introAnimationImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
    introAnimationImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
    introAnimationImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
    introAnimationImageView.translatesAutoresizingMaskIntoConstraints = false
    
    let maskLayer = CAShapeLayer()
    maskLayer.frame = view.bounds
    // Create the frame for the circle.
    let radius: CGFloat = 10.0
    // Rectangle in which circle will be drawn
    let rect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 2 * radius, height: 2 * radius)
    let circlePath = UIBezierPath(ovalIn: rect)
    // Create a path
    let path = UIBezierPath(rect: view.bounds)
    // Append additional path which will create a circle
    path.append(circlePath)
    // Setup the fill rule to EvenOdd to properly mask the specified area and make a crater
    maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
    // Append the circle to the path so that it is subtracted.
    maskLayer.position = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
    maskLayer.path = path.cgPath
    maskLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    
    // Mask our view with Blue background so that portion of red background is visible
    introAnimationImageView.layer.mask = maskLayer
    
    let layerAnimation = CABasicAnimation(keyPath: "transform.scale")
    layerAnimation.fromValue = 1
    layerAnimation.toValue = 50
    layerAnimation.isAdditive = false
    layerAnimation.duration = CFTimeInterval(1)
    layerAnimation.fillMode = .forwards
    layerAnimation.isRemovedOnCompletion = true
    layerAnimation.repeatCount = .infinity
    layerAnimation.autoreverses = true

    maskLayer.add(layerAnimation, forKey: "growingAnimation")

And here's the current output (image still of animation):

Image

How do I expand the CAShapelayer from the center instead of towards the bottom right (from 0,0)?

BaxiaMashia
  • 115
  • 10

1 Answers1

0

Figure it out based off of this Obj-c thread

Changed:

layerAnimation.toValue = 50 // Arbitrary number

To:

layerAnimation.toValue = NSValue(cgPoint: CGPoint(x: view.frame.size.width / 2, y: view.frame.size.height / 2))

Which gives me this (image still of animation):

Image Output

BaxiaMashia
  • 115
  • 10