Animate CAShapeLayer transition

39 Views Asked by At

I have tableView, embed in StackView, stackView.

My tableView height is dynamic(depends on its contentSize) and with alpha(0.3). I need to get shadow on this tableView. I try to add shadow to my stackView, and create a mask to clip shadow outside, but I don't know how to animate it properly. This is code(find it on stackOverflow):

class LayerAnimation: UIStackView {
    let color: CGColor = R.color.detailShadow()!.cgColor
    let opacity: Float = 0.7
    let radius: CGFloat = 15
    let offset: CGSize = CGSize(width: 0, height: 0)
    let shadowView = UIView()

    init() {

        super.init(frame: CGRect.zero)
        shadowView.backgroundColor = .red
        shadowView.layer.shadowColor = color
        shadowView.layer.shadowOpacity = opacity
        shadowView.layer.shadowRadius = radius
        shadowView.layer.shadowOffset = offset
        shadowView.layer.masksToBounds = false
        shadowView.layer.cornerRadius = 15
        self.addSubview(shadowView)
    }

    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setMask() {
        shadowView.frame = bounds
        let inset = -(max(abs(offset.width), abs(offset.height)) + radius) - 20
        // - 10, had to put 10px extra otherwise it would cut shadow
        let maskFrame = bounds.inset(by: UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset))
        let path = CGMutablePath()

        path.addRoundedRect(in: maskFrame, cornerWidth: 15, cornerHeight: 15)
        path.addRoundedRect(in: bounds, cornerWidth: 15, cornerHeight: 15)

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path
        shapeLayer.fillRule = .evenOdd

        self.shadowView.layer.mask = shapeLayer
    }

It works great, if you don't need to move the view, but not in my case, because I need this mask to change with animation. enter image description here

Any help would be greatly appreciated. I've been sitting on this for a few days now

0

There are 0 best solutions below