【发布时间】:2018-08-20 16:03:54
【问题描述】:
我在为 CAGradientLayer 角度设置动画时遇到问题。
CAGradientLayer 中的角度通过起点和终点属性表示。
我想以圆形方式为渐变设置动画。
当我在动画组中设置它时它不起作用。没有动画正在发生。 当我更改
中的属性时DispatchQueue.main.asyncAfter(deadline: now() + 1.0) {
// change properties here
}
它有效。但是一个非常快的动画正在发生。这还不够好。
在网上只有位置和颜色变化,但没有角度变化。
您可以在下面找到一个 Playground 项目来玩
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
// Gradient layer specification
lazy var gradientLayer: CAGradientLayer = {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor.white.withAlphaComponent(0.5).cgColor, UIColor.orange.withAlphaComponent(0.5).cgColor, UIColor.orange.cgColor]
gradientLayer.locations = [0, 0.27, 1]
gradientLayer.frame = view.bounds
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
return gradientLayer
}()
func animationMapFunction(points: [(CGPoint, CGPoint)], keyPath: String) -> [CABasicAnimation] {
return points.enumerated().map { (arg) -> CABasicAnimation in
let (offset, element) = arg
let gradientStartPointAnimation = CABasicAnimation(keyPath: keyPath)
gradientStartPointAnimation.fromValue = element.0
gradientStartPointAnimation.toValue = element.1
gradientStartPointAnimation.beginTime = CACurrentMediaTime() + Double(offset)
return gradientStartPointAnimation
}
}
lazy var gradientAnimation: CAAnimation = {
let startPointAnimationPoints = [(CGPoint(x: 0.0, y: 0.0), CGPoint(x: 1.0, y:0.0)),
(CGPoint(x: 1.0, y:0.0), CGPoint(x: 1.0, y:1.0)),
(CGPoint(x: 1.0, y:1.0), CGPoint(x: 0.0, y:1.0)),
(CGPoint(x: 0.0, y:1.0), CGPoint(x: 0.0, y:0.0))]
let endPointAnimatiomPoints = [(CGPoint(x: 1.0, y:1.0), CGPoint(x: 0.0, y:1.0)),
(CGPoint(x: 0.0, y:1.0), CGPoint(x: 0.0, y:0.0)),
(CGPoint(x: 0.0, y: 0.0), CGPoint(x: 1.0, y:0.0)),
(CGPoint(x: 1.0, y:0.0), CGPoint(x: 1.0, y:1.0))]
let startPointAnimations = animationMapFunction(points: startPointAnimationPoints, keyPath: "startPoint")
let endPointAnimations = animationMapFunction(points: startPointAnimationPoints, keyPath: "endPoint")
let animationGroup = CAAnimationGroup()
animationGroup.duration = 5.0
animationGroup.repeatCount = Float.infinity
animationGroup.animations = startPointAnimations + endPointAnimations
return animationGroup
}()
override func loadView() {
let view = UIView(frame: UIScreen.main.bounds)
self.view = view
view.layer.addSublayer(gradientLayer)
}
func animate() {
view.layer.removeAllAnimations()
gradientLayer.add(gradientAnimation, forKey: nil)
}
}
// Present the view controller in the Live View window
let vc = MyViewController()
PlaygroundPage.current.liveView = vc
vc.animate()
【问题讨论】:
-
这更像是一个数学问题,而不是一个 Swift 问题。您需要创建一个方法,该方法采用角度并返回相反方向的两个 CGPoints
-
没有。关键是,无论我输入什么值。没有任何效果。它就像属性是不可动画的。这些值是正确的,与“数学”无关
-
这就是为什么我说要手动设置动画
-
我不明白“手动制作动画”是什么意思?
-
我认为你唯一的选择是使用计时器。
标签: swift calayer cabasicanimation caanimation cagradientlayer