具有负M_PI的CGAffineTransformMakeRotation

gpb*_*pbl 5 uiview cgaffinetransform ios swift ios8

我正在使用CGAffineTransformMakeRotation旋转UIView动画块内部,我想逆时针旋转它180º.

但是当我放

myView.animateWithDuration(0.5)
myView.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI))
Run Code Online (Sandbox Code Playgroud)

它仍然顺时针旋转.令我感到困惑的是,如果我"手动"写入值M_PI,它就会按预期工作

 // this will rotate counterclockwise
 myView.transform = CGAffineTransformMakeRotation(CGFloat(-3.14159265358979))
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

编辑:添加我正在使用动画块

luk*_*302 9

正如我在第一篇评论中所说,并且Segii已经写过:动画将采用它现在的值和它试图去的位置之间的最短距离.imho的最佳解决方案是CABasicAnimation用于强制逆时针旋转:

let anim = CABasicAnimation(keyPath: "transform.rotation")
anim.fromValue = M_PI
anim.toValue = 0
anim.additive = true
anim.duration = 2.0

myView.layer.addAnimation(anim, forKey: "rotate")
myView.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI))
Run Code Online (Sandbox Code Playgroud)

这将一次逆时针旋转180°.

您在最后一行指定的角度+ fromValue是起始角度 - > 0.然后旋转将移动距离(toValue - fromValue) = 0 - M_PI = - M_PI- >逆时针旋转180度.


Ser*_* Jr 5

据我所知,你正试图在动画块中旋转视图.animateWithDuration将始终以最短的方式执行动画.因此,M_PI和-M_PI给出相同的目标位置.原因是,为什么在手动设置时获得预期的动画方向是您的手动值实际上小于M_PI,因此最短的旋转方式是逆时针方向.

要获得预期的行为,您必须链接至少两个动画,分割您的旋转角度.例如

//first animation block
myView.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI/2))CGAffineTransformMakeRotation;
//second animation block
myView.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI/2))CGAffineTransformMakeRotation;
Run Code Online (Sandbox Code Playgroud)

Swift 3.0

myView.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI/2))
Run Code Online (Sandbox Code Playgroud)

或者,更可靠的是,使用CAKeyframeAnimation