Search code examples
iosuiviewcatransform3dcatransform3drotate

How to get proper z-ordering CATransform3D


When I apply a CATransform3DRotate around the y-axis to two UIViews, their z-ordering seems to be reversed. The sections of the UIView that have been rotated back into the z-axis appear in front of the sections that have rotated towards the screen. This animation shows what I mean:

rotation animation

How do I get it so that z-ordering behaves as expected?

The code I used to generate that animation is below (the double [UIView animateWithDuration] is just needed to properly to a full rotation):

@interface ViewController ()

@property (strong, nonatomic) UIView *blueSquare;
@property (strong, nonatomic) UIView *redSquare;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.blueSquare = [[UIView alloc] initWithFrame:(CGRect){.origin = {160,234}, .size = {400,300}}];
    self.blueSquare.backgroundColor = [UIColor blueColor];
    [self.view addSubview:self.blueSquare];

    self.redSquare = [[UIView alloc] initWithFrame:(CGRect){.origin = {464,234}, .size = {400,300}}];
    self.redSquare.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.redSquare];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    [UIView animateWithDuration:5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        CATransform3D transform = CATransform3DIdentity;

        transform.m34 = 1.0/900.0;  // for perspective

        transform = CATransform3DRotate(transform, M_PI, 0, 1, 0);

        self.blueSquare.layer.transform = transform;
        self.redSquare.layer.transform = transform;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
            CATransform3D transform = CATransform3DIdentity;

            transform.m34 = 1.0/900.0;  // for perspective

            transform = CATransform3DRotate(transform, 2*M_PI-0.001, 0, 1, 0);

            self.blueSquare.layer.transform = transform;
            self.redSquare.layer.transform = transform;
        } completion:nil];
    }];
}

@end

Solution

  • The perspective in your transforms are inversed. Normally you would use a negative value for the m34 (3rd column, 4th row in the transform matrix) component of the transform.