Gradient Animation

We are going to create a gradient animation. It's kind of like the old "slide to unlock" label on the lock screen.

1. Configure a gradient Layer

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

This defines the orientation of the gradient and its start and end points.

15126498638113.jpg

Then add the colors to the layer

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

And its locations

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

Now it looks like this:


15126500806935.jpg

Add the following code to layoutSubviews()

gradientLayer.frame = bounds

and the following to didMoveToWindow():

layer.addSublayer(gradientLayer)

2. Animate gradients

CAGradientLayer offers four animatable properties:

  • colors: Animate the gradient’s colors to give it a tint.
  • locations: Animate the color milestone locations to make the colors move
    around inside the gradient.
  • startPoint and endPoint: Animate the extents of the layout of the gradient.

Add the following code to the end of didMoveToWindow()

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)

Now it finally animates but not quite what we want it to be. We want to change the gradientLayer's frame larger to make the animation look nicer:

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

3. Create a text mask

First we create a new constant property:

let textAttributes: [String: AnyObject] = {
  let style = NSMutableParagraphStyle()
  style.alignment = .center
  return [
    NSFontAttributeName: UIFont(
      name: "HelveticaNeue-Thin",
      size: 28.0)!,
    NSParagraphStyleAttributeName: style
  ]
}()

Then we need to create a temporary graphic context to render the text as an image.
Add the following code to setNeedsDisplay():

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

Now use that image to create a mask on your gradient layer:

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

Finally add one last line to set the new layer as a mask for the gradient:

gradientLayer.mask = maskLayer

And...We're done!

final.gif

See code in here.

你可能感兴趣的:(Gradient Animation)