Search code examples
iphoneioscalayercatransform3d

how to rotate a view from left to right using CATransform3DMakeRotation


I know how to rotate a view from right to left

CATransform3D transform = CATransform3DIdentity;
transform = CATransform3DMakeRotation(M_PI, 0.0f, 1.0f, 0.0f);
transform.m34 = 0.0015;
view.layer.transform = transform;

But i cant rotate it from left to right. Please help me.


Solution

  • I'm not sure what you mean by “left to right” and “right to left”. Anyway, as you have discovered, you can't control the direction of the animation just by setting the transform matrix, because both -M_PI and +M_PI have the same final effect, so there's no way for Core Animation to reliably know which way you want it to rotate.

    Instead, you can animate the transform.rotation.y key path of the layer. This is a little more complicated to do, particularly since you want to animate a view's layer instead of a freestanding layer (not controlled by a view).

    Anyway, here's the code I tested:

    - (IBAction)rotateButtonWasTapped:(id)sender {
        // Establish the perspective to be used during the animation.
        CATransform3D transform = CATransform3DIdentity;
        transform.m34 = 0.0015;
        self.imageView.layer.transform = transform;
    
        static CGFloat kAngle = -M_PI;
    
        [CATransaction begin]; {
            // After the animation completes, make the transform “permanent”.  Otherwise it
            // will be undone when the animation is removed from the layer.
            [CATransaction setCompletionBlock:^{
                self.imageView.layer.transform = CATransform3DRotate(transform, kAngle, 0, 1, 0);
            }];
    
            // Animate the rotation using Core Animation's extension to Key Value Coding.
            // The sign of kAngle determines the direction of rotation.
            CABasicAnimation *animation = [CABasicAnimation
                animationWithKeyPath:@"transform.rotation.y"];
            animation.fromValue = @0;
            animation.toValue = @(kAngle);
            animation.duration = 1;
            [self.imageView.layer addAnimation:animation forKey:animation.keyPath];
        } [CATransaction commit];
    }
    

    This rotates the view such that the left edge of the view moves “closer” to the user during the rotation. If that's not what you mean by “left to right”, change the definition of kAngle to M_PI and it will rotate in the other direction. I have tested both ways. You can even spin the layer multiple times in one animation. For example, try defining kAngle as -3 * M_PI.