【问题标题】:How to make an animation shadowOffset in Swift?如何在 Swift 中制作动画 shadowOffset?
【发布时间】:2020-05-23 16:02:59
【问题描述】:

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

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. 阴影路径
  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。

最终的 O/P

编辑:

如果您希望阴影在指定动画后仍保持其位置

  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)
    }

最终的 O/P 如下所示:

【讨论】:

  • Sandeep Bhandari 非常感谢,现在我明白了它是如何工作的
  • @nikolay-nikolaenko:如果对你有帮助,请接受我的回答:)
  • 你好@SandeepBhandari,你能帮我解决同样的问题但使用shadowPath吗?我需要动画 UIView 垂直增长的阴影边框:stackoverflow.com/questions/65492182/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2015-10-18
  • 1970-01-01
相关资源
最近更新 更多