Melany
Melany

Reputation: 466

CALayer clip subviews in animation

I want to make animation, that should look like that: there a layer on the mainViewLayer, drawn Drop of water with transparent fillColor, I add under it another CAShapeLayer - with blue Color, there layers have the same bounds. and i want to animate its y position, that will imitate decreasing of water level.

    fallingWaterLayer = CAShapeLayer()
    fallingWaterLayer.frame = x.bounds
    fallingWaterLayer.fillColor = UIColor.blue.cgColor
    let path = CGPath(rect:fallingWaterLayer.bounds, transform:nil)
    fallingWaterLayer.path = path
    x.layer.addSublayer(fallingWaterLayer)
    mainLayer = DropLayer(x.bounds, shouldFillLayer:false)
    x.layer.addSublayer(mainLayer!)

enter image description here

my animation looks like that:

    let animation = CABasicAnimation(keyPath: "bounds.origin.y")
    animation.toValue = x.bounds.size.width * -1
    animation.duration = 5.8
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
    animation.fillMode = kCAFillModeBoth
    animation.isRemovedOnCompletion = false
    fallingWaterLayer.add(animation, forKey: animation.keyPath)

So the question is how can i make top Layer clips the blue rect, to make it look like animation is done inside the Drop of water?

Upvotes: 0

Views: 1106

Answers (1)

Nick Lockwood
Nick Lockwood

Reputation: 41005

Every CALayer has a mask property, which can be any arbitrary other layer, so that seems like it would be a good solution.

https://developer.apple.com/reference/quartzcore/calayer/1410861-mask

The way the mask property works is that any transparent pixel of the mask will be clipped in the target layer. So you'll need to create a second, solid water drop layer to use as the mask - you can't re-use the same water drop outline, otherwise the water will be clipped to just the border of the water drop, instead of filling the inside.

Upvotes: 1

Related Questions