iOS Swift在非线性路径中对视图进行动画处理

问题描述:

我试图像这样通过非线性路径为UIView设置动画(我没有尝试绘制路径本身):

I am trying to animate a UIView through non linear path(i'm not trying to draw the path itself) like this :

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

The initial position of the view is determinated using a trailing and bottom constraint (viewBottomConstraint.constant == 100 & viewTrailingConstraint.constant == 300) I am using UIView.animatedWithDuration like this :

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

但是它会以线性路径为视图设置动画.

But it animate the view in a linear path.

您可以将keyFrame动画与路径一起使用

You can use keyFrame animation with path

    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)是终点

(cpx,cpy) is control point,and (x,y) is end point