Ios Swift在非线性路径中为视图设置动画

时间:2015-12-02 13:55:46

标签: ios swift animation uiview

我试图通过非线性路径(我不是试图绘制路径本身)来动画UIView,如下所示:

object animated through a curve

使用尾随和底部约束(viewBottomConstraint.constant == 100& viewTrailingConstraint.constant == 300)确定视图的初始位置 我正在使用这样的UIView.animatedWithDuration

viewTrailingConstraint.constant = 20
viewBottomConstraint.constant = 450
UIView.animateWithDuration(1.5,animation:{
    self.view.layoutIfNeeded()
},completition:nil)

但它以线性路径为视图设置动画。

2 个答案:

答案 0 :(得分:11)

您可以将keyFrame动画与路径

一起使用
    let keyFrameAnimation = CAKeyframeAnimation(keyPath:"position")
    let mutablePath = CGPathCreateMutable()
    CGPathMoveToPoint(mutablePath, nil,50,200)
    CGPathAddQuadCurveToPoint(mutablePath, nil,150,100, 250, 200)
    keyFrameAnimation.path = mutablePath
    keyFrameAnimation.duration = 2.0
    keyFrameAnimation.fillMode = kCAFillModeForwards
    keyFrameAnimation.removedOnCompletion = false
    self.label.layer.addAnimation(keyFrameAnimation, forKey: "animation")

的Gif

关于此功能

void CGContextAddQuadCurveToPoint (
   CGContextRef _Nullable c,
   CGFloat cpx,
   CGFloat cpy,
   CGFloat x,
   CGFloat y
);

(cpx,cpy)是控制点,(x,y)是终点 enter image description here

答案 1 :(得分:5)

Leo使用Core Animation和CAKeyframeAnimation的答案很好,但是它在视图的“表示层”上运行,并且只创建将视图移动到新位置的外观。在动画完成后,您需要添加额外的代码才能将视图实际移动到最终位置。加上核心动画是复杂和令人困惑的。

我建议使用UIView方法 animateKeyframesWithDuration:delay:options:animations:completion:。您可能希望使用选项值UIViewKeyframeAnimationOptionCalculationModeCubic,这会导致对象沿着通过所有点的弯曲路径移动。

您在视图中调用它,然后在动画块中,多次调用addKeyframeWithRelativeStartTime:relativeDuration:animations:,将视图移动到曲线上的点。

我在github上有一个示例项目,展示了这个和其他技术。它被称为KeyframeViewAnimations(链接)

相关问题