Rotating a CALayer 90 degrees?

2019-03-22 15:25发布

How do I rotate a CALayer 90 degrees? I need to rotate everything include sublayers and the coordinate system.

5条回答
做个烂人
2楼-- · 2019-03-22 15:46

Rab showed how do do it with a CAAnimation object. Its actually simpler than that:

[myView animateWithDuration: 0.25 
  animations:
  ^{
     myView.transform = CGAffineTransformMakeRotation(M_PI/2);
   }
];

(lifting the transform line from Chris's answer - too lazy to rewrite it since he already provided the perfect code.)

Chris's code would rotate the view without animation. My code above will do the same thing with animation.

By default, animations use ease in, ease out timing. You can change that with a slightly more complex version of the animateWithDuration call (Use animateWithDuration:delay:options:animations:completion: instead, and pass in a the desired timing in the options parameter.)

查看更多
女痞
3楼-- · 2019-03-22 15:50

Basically something like that:

CGAffineTransform rotateTransform = CGAffineTransformMakeRotation(M_PI / 2.0); [myCALayer setAffineTransform:rotateTransform];

EDIT: It'll rotate clockwise or counter-clockwise depending on the platform (iOS or Mac OS).

查看更多
干净又极端
4楼-- · 2019-03-22 15:53

Obj-C:

theLayer.transform = CATransform3DMakeRotation(90.0 / 180.0 * M_PI, 0.0, 0.0, 1.0);

Swift:

theLayer.transform = CATransform3DMakeRotation(90.0 / 180.0 * .pi, 0.0, 0.0, 1.0)

That is, transform the layer such that it is rotated by 90 degrees (π / 2 radians), with 100% of that rotation taking place around the z-axis.

查看更多
欢心
5楼-- · 2019-03-22 15:58

To rotate 90' right:

myView.transform = CGAffineTransformMakeRotation(M_PI_2);
查看更多
老娘就宠你
6楼-- · 2019-03-22 16:01

If I'm animating it I use something like this in my apps:

- (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;
}

Of course you can use it anywhere, don;t have to return it from a method if that doesn;t suit your needs.

查看更多
登录 后发表回答