我想为路径旁的视图(没有CAKeyframeAnimation
)设置动画,而不是使用UIViewPropertyAnimator
。
为此,我有一个带有起点和终点的路径以及一个制作四曲线的控制点。
let path = UIBezierPath()
path.move(to: view.center)
path.addQuadCurve(to: target.center, controlPoint: CGPoint(x: view.center.x-10, y: target.center.y+160))
我的动画师使用UIView.animateKeyframes动画对路径旁的位置进行动画处理。
let animator = UIViewPropertyAnimator(duration: duration, curve: .easeIn)
animator.addAnimations {
UIView.animateKeyframes(withDuration: duration, delay: 0, options: [.calculationModeLinear], animations: {
let points = 100
for i in 1...points {
let pos = Double(i)/Double(points)
let x = self.quadBezier(pos: pos,
start: Double(view.center.x),
con: Double(view.center.x-10),
end: Double(target.center.x))
let y = self.quadBezier(pos: pos,
start: Double(view.center.y),
con: Double(target.center.y+160),
end: Double(target.center.y))
let duration = 1.0/Double(points)
let startTime = duration * Double(i)
UIView.addKeyframe(withRelativeStartTime: startTime, relativeDuration: duration) {
view.center = CGPoint(x: x, y: y)
}
}
})
}
要计算点,我使用与@rmaddy相同的功能,请认为此处具有相同的source。
func quadBezier(pos: Double, start: Double, con: Double, end: Double) -> Double {
let t_ = (1.0 - pos)
let tt_ = t_ * t_
let tt = pos * pos
return Double(start * tt_) + Double(2.0 * con * t_ * pos) + Double(end * tt)
}
首先,我认为计算是错误的,因为感觉就像计算出的点通过了控制点之类的东西:
但是在遍历相同的forloop并将蓝点添加到计算出的x / y位置后,表明该位置是正确的。
所以我想知道为什么我的动画不遵循该路径。
我找到了这个question,并将我的问题发布为答案,但是我猜没有人意识到这一点。
答案 0 :(得分:2)
View.center在动画过程中发生了变化,将其修复然后没有问题:
try the following:
let cent = view.center
UIView.animateKeyframes(withDuration: duration, delay: 0, options: [.beginFromCurrentState], animations: {
let points = 100
for i in 1...points {
let pos = Double(i)/Double(points)
let x = self.quadBezier(pos: pos,
start: Double(cent.x), //here
con: Double(cent.x-10), //here
end: Double(square.center.x))
let y = self.quadBezier(pos: pos,
start: Double(cent.y), //here
con: Double(square.center.y+160),
end: Double(square.center.y))
let duration = 1.0 / Double(points)
let startTime = duration * Double(i)
print("Animate: \(Int(x)) : \(Int(y))")
UIView.addKeyframe(withRelativeStartTime: startTime, relativeDuration: duration) {
view.center = CGPoint(x: x, y: y)
}
}
})
}