【问题标题】:UIView: animate a gradient inifinitely in the same given direction?UIView:在相同的给定方向上无限动画渐变?
【发布时间】:2021-11-10 18:50:15
【问题描述】:

我想将CAAnimation 添加到渐变并将其应用到UIView,如下所示:

思路是20%的渐变是全白的,全蓝的部分是从左向右移动,到屏幕右边缘(动画结束)的时候,我想给用户再次从左边缘开始的感觉(再次开始动画)。

然而,当谈到CAGradientLayer 时,我是一个完整的初学者,所以我真的不知道该怎么做。这是我写的,但离我想要的还很远。

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)

还有最后一个问题,如果我使用isHidden 属性隐藏包含CAGradientLayerUIView,它实际上并没有从屏幕上删除该层。我该怎么做?

非常感谢您的帮助

【问题讨论】:

  • 你所拥有的是动画的良好基础。但是您的其余代码毫无意义。特别是您创建 loadingView 然后您从不使用它;你把它扔掉。很难看出你的期望
  • 看看这个答案:stackoverflow.com/a/67959614/6257435 ...ShimmerButton 类似乎完全符合您的要求。 (我不知道为什么它被否决了,或者为什么它从未被接受,因为它直接解决了该用户的问题)。
  • @DonMag 我遵循了这个例子,它完全符合我的需求。非常感谢!

标签: ios uiview caanimation cagradientlayer


【解决方案1】:

创建一个背景为蓝色的LoadingView。创建一个带有白色组件的透明渐变:

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)

添加渐变层:

loadingView.layer.addSublayer(gradient)

像这样动画层的移动:

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")

【讨论】:

    猜你喜欢
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多