如何在Swift中制作动画shadowOffset?

问题描述 投票:0回答:1

我写了代码,但我不明白为什么它不工作......

func animate(vc: UIView) {
    vc.layer.shadowColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
    vc.layer.shadowRadius = 5
    vc.layer.shadowOffset = CGSize(width: 0, height: 0)
    let animationX = CABasicAnimation()
    animationX.keyPath = "shadowOffset"
    animationX.fromValue = vc.layer.shadowOffset
    animationX.toValue = CGSize(width: 10, height: 10)
    animationX.duration = 1
    vc.layer.add(animationX, forKey: animationX.keyPath)
}

@IBAction func buttonTapped(_ sender: UIButton) {
  animate(vc: sender)
}

有人知道这是如何工作的吗?

swift cabasicanimation
1个回答
1
投票

少了一些东西

  1. 影子路径
  2. 阴影透明度
        vc.layer.masksToBounds = false
        vc.layer.shadowColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
        vc.layer.shadowRadius = 5
        vc.layer.shadowOffset = CGSize(width: 0, height: 0)
        vc.layer.shadowPath = UIBezierPath(rect: vc.bounds).cgPath
        vc.layer.shadowOpacity = 1.0
        let animationX = CABasicAnimation()
        animationX.keyPath = "shadowOffset"
        animationX.fromValue = vc.layer.shadowOffset
        animationX.toValue = CGSize(width: 10, height: 10)
        animationX.duration = 1
        vc.layer.add(animationX, forKey: animationX.keyPath)

默认情况下 shadowOpacity 是0。

最后的OP

enter image description here

EDIT:

如果你想让影子在动画结束后也能保持在它的位置上,请注明

  1. 填充模式
  2. isRemovedOnCompletion

最终代码将是这样的

func animate(vc: UIView) {
        vc.layer.masksToBounds = false
        vc.layer.shadowColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
        vc.layer.shadowRadius = 5
        vc.layer.shadowOffset = CGSize(width: 0, height: 0)
        vc.layer.shadowPath = UIBezierPath(rect: vc.bounds).cgPath
        vc.layer.shadowOpacity = 1.0
        let animationX = CABasicAnimation()
        animationX.keyPath = "shadowOffset"
        animationX.fromValue = vc.layer.shadowOffset
        animationX.toValue = CGSize(width: 10, height: 10)
        animationX.duration = 1
        animationX.fillMode = .forwards
        animationX.isRemovedOnCompletion = false
        vc.layer.add(animationX, forKey: animationX.keyPath)
    }

最后的OP看起来像。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.