简体   繁体   中英

UIView: animate a gradient inifinitely in the same given direction?

I would like to add a CAAnimation to a gradient and apply it to a UIView , looking like this:

在此处输入图片说明

The idea is that 20% of the gradient is fully white, and the fully blue part moves from left to right, and when it comes to the right edge of the screen (end of animation), I want to give the user the feeling that it's starting from the left edge again (start of animation again).

I am however a complete beginner when it comes to CAGradientLayer , so I don't really know what to do. This is what I wrote but it's still far from what I want to achieve.

let loadingView = UIView(frame: frame)
let gradient = CAGradientLayer()     
gradient.frame = frame
gradient.colors = [UIColor.blue.cgColor, UIColor.white.cgColor]
gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
gradient.locations = [0.0, 0.5, 1.0]
let animation = CABasicAnimation(keyPath: "locations")
animation.fromValue = [0.0, 0.5]
animation.toValue = [0.0, 1.0]
animation.duration = 1.5
animation.autoreverses = false
animation.repeatCount = .infinity
gradient.add(animation, forKey: nil)
view.layer.addSublayer(gradient)

Also one last question, if I hide the UIView containing the CAGradientLayer using the isHidden property, it doesn't actually remove that layer from the screen. How can I do this?

Thank you very much for your help

Create a LoadingView with a blue background color. Create a transparent gradient with a white component:

let gradient = CAGradientLayer()
gradient.frame = loadingView.frame
gradient.colors = [
    UIColor.white.withAlphaComponent(0), // It is important to use white, not clear color
    UIColor.white, 
    UIColor.white.withAlphaComponent(0)
].map { $0.cgColor }
gradient.locations = [0.0, 0.5, 1.0] // The number of locations matches the number of colors
// Horizontal direction
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1.0, y: 0)

Add a gradient layer:

loadingView.layer.addSublayer(gradient)

Animate the movement of the layer like this:

let animation = CABasicAnimation(keyPath: "transform.translation.x")
animation.fromValue = -loadingView.frame.width
animation.toValue = loadingView.frame.width
animation.duration = 1.5
animation.repeatCount = .infinity

gradient.add(animation, forKey: "loadingAnimation")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM