[英]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:我想将CAAnimation
添加到渐变并将其应用于UIView
,如下所示:
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).思路是20%的渐变为全白,全蓝部分从左向右移动,到了屏幕右边缘(动画结束),我想给用户的感觉是它再次从左边缘开始(再次开始动画)。
I am however a complete beginner when it comes to CAGradientLayer
, so I don't really know what to do.然而,当谈到CAGradientLayer
时,我是一个完整的初学者,所以我真的不知道该怎么做。 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.还有最后一个问题,如果我使用isHidden
属性隐藏包含CAGradientLayer
的UIView
,它实际上不会从屏幕上删除该层。 How can I do this?我怎样才能做到这一点?
Thank you very much for your help非常感谢您的帮助
Create a LoadingView
with a blue background color.创建一个带有蓝色背景色的LoadingView
。 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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.