如何为增加其宽度的渐变层设置动画?

时间:2018-07-06 11:10:58

标签: swift animation

我正在使用一个简单的UIView进行动画处理,并在其中添加了一个渐变层。 我想增加视图的宽度以及放置在视图上的图层, 但是我得到的只是视图增加了它的宽度,而不是增加了层数。

示例:假设我有一个UIView和一个height = width = 50 通过将宽度设置为width += 50来设置动画。该动画正在工作。如果我对图层执行相同操作,则会发生注意。该层不会增加其宽度。我尝试了一些方法来解决此问题(请参见代码中的注释),但没有任何效果。

这是我的代码

func performNextTitleAnimation() {

        let overlayViewHeight = overlayView.frame.size.height
        let overlayViewWidth = overlayView.frame.size.width
        let animationHeight: CGFloat = 48
        let overlayViewHalfHeight = (overlayViewHeight) / 2

        swipeAnimation = UIView(frame: CGRect(x: 0, y: overlayViewHalfHeight - (animationHeight/2), width: 48, height: animationHeight))

        swipeAnimation.backgroundColor = .gray

        swipeAnimation.layer.cornerRadius = swipeAnimation.frame.size.height / 2

        gradientLayer.frame = swipeAnimation.bounds

        overlayView.addSubview(swipeAnimation)
        swipeAnimation.layer.addSublayer(gradientLayer)

        UIView.animate(withDuration: 1.2, delay: 0, options: [.repeat], animations: {
            self.gradientLayer.cornerRadius = 24

            self.swipeAnimation.frame.size.width += 50

            //Things I tried, but not working
            //1.) self.gradientLayer.frame.size.width += 50
            //2.) self.gradientLayer.frame.size.width = self.swipeAnimation.frame.size.width
            //3.) self.gradientLayer.bounds = self.swipeAnimation.bounds

        }, completion: nil)
    }

渐变层

gradientLayer.colors = [UIColor.white.cgColor, animationColor.cgColor]
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.transform = CATransform3DMakeRotation(3*(CGFloat.pi) / 2, 0, 0, 1)

我们非常感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

我需要为CAGrandientLayer设置动画时取得的最好结果是将其用作自定义UIView的layerClass:

class GrandientView: UIView {
  override class var layerClass : AnyClass {
    return CAGradientLayer.self
  }

  var gradientLayer: CAGradientLayer {
    // it is safe to force cast here
    // since we told UIView to use this exact type
    return self.layer as! CAGradientLayer
  }

  override init(frame: CGRect) {
    super.init(frame: frame)
    // setup your gradient
  }
}