如何将CALayer旋转90度?我需要旋转包括子层和坐标系在内的所有内容。
如何将CALayer旋转90度?我需要旋转包括子层和坐标系在内的所有内容。
Obj-C:
theLayer.transform = CATransform3DMakeRotation(90.0 / 180.0 * M_PI, 0.0, 0.0, 1.0);
Swift:
->Swift:
theLayer.transform = CATransform3DMakeRotation(90.0 / 180.0 * .pi, 0.0, 0.0, 1.0)
也就是说,将该层进行旋转使其绕z轴旋转90度(π / 2弧度),并且该旋转的100%发生在z轴周围。
M_PI
被乘以一个double
类型,因此它被扩展了,这就破坏了类型转换的目的。 - Jonathan GrynspanType.pi
或.pi
,这将使用正确的类型(在本例中为CGFloat.pi
)。 - Abhi Beckert.anchor
设置为帧的中心 - Fattie如果我需要在我的应用程序中进行动画处理,我会使用类似于以下的代码:
- (NSObject *) defineZRotation {
// Define rotation on z axis
float degreesVariance = 90;
// object will always take shortest path, so that
// a rotation of less than 180 deg will move clockwise, and more than will move counterclockwise
float radiansToRotate = DegreesToRadians( degreesVariance );
CATransform3D zRotation;
zRotation = CATransform3DMakeRotation(radiansToRotate, 0, 0, 1.0);
// create an animation to hold "zRotation" transform
CABasicAnimation *animateZRotation;
animateZRotation = [CABasicAnimation animationWithKeyPath:@"transform"];
// Assign "zRotation" to animation
animateZRotation.toValue = [NSValue valueWithCATransform3D:zRotation];
// Duration, repeat count, etc
animateZRotation.duration = 1.5;//change this depending on your animation needs
// Here set cumulative, repeatCount, kCAFillMode, and others found in
// the CABasicAnimation Class Reference.
return animateZRotation;
}
当然可以在任何地方使用它,如果不适合您的需求,就不必从方法中返回它。
基本上就像这样:
CGAffineTransform rotateTransform = CGAffineTransformMakeRotation(M_PI / 2.0);
[myCALayer setAffineTransform:rotateTransform];
编辑:它将根据平台(iOS或Mac OS)顺时针或逆时针旋转。
向右旋转90度:
myView.transform = CGAffineTransformMakeRotation(M_PI_2);
CAAnimation
对象来实现。实际上,它比那更简单:[myView animateWithDuration: 0.25 animations: ^{ myView.transform = CGAffineTransformMakeRotation(M_PI/2); }];
(从Chris的答案中提取变换行 - 太懒了,因为他已经提供了完美的代码。)
Chris的代码可以旋转视图而不带动画。我上面的代码将使用动画执行相同的操作。
默认情况下,动画使用缓入缓出的时间。您可以使用稍微更复杂的版本的animateWithDuration
调用进行更改(使用animateWithDuration:delay:options:animations:completion:
代替,并在options参数中传递所需的时间)。