Steve Left
Steve Left

Reputation: 11

CALayer Mask Animation not disappearing

Ive set up a splash screen like twitters opening, and it runs fine, but once the animation is complete, the mask returns to normal and doesn't disappear after widening. Here is the code for the mask & animation:

override func viewDidLoad() {
    super.viewDidLoad()

    //setting up the arm mask
    imageView.image = UIImage(named: "placeholderbg.png")

    self.mask = CALayer()
    self.mask?.contents = UIImage(named: "arm.png")?.cgImage
    self.mask?.bounds = CGRect(x: 0, y: 0, width: 120, height: 100)
    self.mask?.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    self.mask?.position = CGPoint(x: view.frame.size.width/2, y: view.frame.size.height/2)
    imageView.layer.mask = mask

    //animation of the mask
    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
        let keyFrameAnimation = CAKeyframeAnimation(keyPath: "bounds")
        keyFrameAnimation.duration = 1
        keyFrameAnimation.timingFunctions =
        [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
        CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)]

        let initialBounds = NSValue(cgRect: self.mask!.bounds)
        let secondBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 110, height: 90))
        let finalBounds = NSValue(cgRect: CGRect(x: 0, y: 0, width: 6000, height: 5000))
        keyFrameAnimation.values = [initialBounds, secondBounds, finalBounds]
        keyFrameAnimation.keyTimes = [0, 0.3, 1]
        self.mask!.add(keyFrameAnimation, forKey: "bounds")        
    }
}

image of what the mask returns to after animation is complete instead of disappearing

Upvotes: 1

Views: 167

Answers (1)

matt
matt

Reputation: 535306

As with any animation, when the animation is over it is removed from the render tree and the "true" state of affairs is revealed. It is up to you to set the animated layer's true state to its final state, so that when the animation reaches its final frame and is removed, that final frame is matched by the layer's true state.

You are not doing that. You add the bounds animation to the mask layer, but you do not change the mask's real bounds. So when the animation ends, the mask layer appears to jump back to its initial bounds — because you never changed them.

As for the "disappear" part, it's hard to tell what you mean, but it's likely a different matter; I don't see anything in your code that would make the mask "disappear" so I'm not clear on what you expect. If you want something new to happen at the end of the animation, you need to attach a completion function to it.

Upvotes: 1

Related Questions