iOS动画:Gradient渐变动画(8)

有没有想过iPhone屏幕滑动解锁动画是怎么实现的呢?
image_1
没错,它就是这一节的重点。

首先我们创建一个CAGradientLayer的对象gradientLayer,并为其设置起始点和结束点

	gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
	gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)

这样就定义了渐变的方向。
image_2
现在来为渐变定义colors

	let colors = [
	  UIColor.black.cgColor,
      UIColor.white.cgColor,
      UIColor.black.cgColor
    ]
	gradientLayer.colors = colors

上面的颜色以黑色开始,后渐变为白色,最后渐变黑色。
现在我们来设置每种颜色在渐变中的确切位置

    gradientLayer.colors = colors
    let locations: [NSNumber] = [
      0.25,
      0.5,
      0.75
    ]
    gradientLayer.locations = locations

颜色转折点如图:
image_3
将gradientLayer加入view的layer图层

gradientLayer.frame = CGRect(
      x: -bounds.size.width,
      y: bounds.origin.y,
      width: 3 * bounds.size.width,
      height: bounds.size.height)
layer.addSublayer(gradientLayer)

为gradientLayer添加渐变动画

    let gradientAnimation = CABasicAnimation(keyPath: "locations")
    gradientAnimation.fromValue = [0.0, 0.0, 0.25]
    gradientAnimation.toValue = [0.75, 1.0, 1.0]
    gradientAnimation.duration = 3.0
    gradientAnimation.repeatCount = Float.infinity
    
    gradientLayer.add(gradientAnimation, forKey: nil)

创建文字

      let image = UIGraphicsImageRenderer(size: bounds.size)
        .image { _ in
          text.draw(in: bounds, withAttributes: textAttributes)
        }

      let maskLayer = CALayer()
      maskLayer.backgroundColor = UIColor.clear.cgColor
      maskLayer.frame = bounds.offsetBy(dx: bounds.size.width, dy: 0)
      maskLayer.contents = image.cgImage

      gradientLayer.mask = maskLayer

这就完成啦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值