iosobjective-cswiftcatransform3dcatransform3drotate

CATransform3D perspective not working on CATransformLayer


Note : Please ignore colors, gradients and size! My concern is perspective is not worked as expected

I am trying to achieve output as bellow,

enter image description here

But when I run my code it is giving me following output

enter image description here

Have a look at my code please :

CATransformLayer *baseLayer = [CATransformLayer layer];
baseLayer.anchorPoint = CGPointZero;
baseLayer.bounds = self.view.bounds;
baseLayer.position = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds));

[self.view.layer addSublayer:baseLayer];

CALayer *redLayer = [CALayer layer];
redLayer.backgroundColor = [UIColor redColor].CGColor;
redLayer.frame = CGRectMake(0, 0, 100, 100);
redLayer.position = CGPointMake(0,0);
redLayer.anchorPoint = CGPointMake(1, 0.5); // right
[baseLayer addSublayer:redLayer];

CALayer *blueLayer = [CALayer layer];
blueLayer.backgroundColor = [UIColor blueColor].CGColor;
blueLayer.bounds = CGRectMake(0, 0, 600, 100);
blueLayer.anchorPoint = CGPointMake(1, 0.5); // right
blueLayer.position = CGPointMake(-50,0);
[baseLayer addSublayer:blueLayer];

CATransform3D transform = CATransform3DIdentity;
transform.m34 = -1/80;
transform = CATransform3DRotate(transform, -M_PI_2, 0, 1, 0);
blueLayer.transform = transform;

baseLayer.sublayerTransform = CATransform3DRotate(CATransform3DIdentity, degreesToRadians(80), 0, 1, 0);

Solution

  • I Don't what makes this issue resolved but here is my updated code it is working as expected.

    CATransformLayer *baseLayer = [CATransformLayer layer];
    baseLayer.anchorPoint = CGPointZero;
    baseLayer.bounds = self.view.bounds;
    baseLayer.position = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds));
    
    CALayer *redLayer = [CALayer layer];
    redLayer.backgroundColor = [UIColor redColor].CGColor;
    redLayer.frame = CGRectMake(0, 0, 1000, 250);
    redLayer.position = CGPointMake(0,0);
    redLayer.anchorPoint = CGPointMake(0, 0.5); // right
    redLayer.transform = CATransform3DRotate(CATransform3DIdentity, M_PI_2,0.0f, 1.0f, 0.0f);
    [baseLayer addSublayer:redLayer];
    
    CALayer *blueLayer = [CALayer layer];
    blueLayer.backgroundColor = [UIColor blueColor].CGColor;
    blueLayer.bounds = CGRectMake(0, 0, 125, 250);
    blueLayer.anchorPoint = CGPointMake(0, 0.5); // right
    blueLayer.position = CGPointMake(0,0);
    [baseLayer addSublayer:blueLayer];
    
    CGFloat perspective = -1000.0; //This relates to the m34 perspective matrix.
    
    CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
    rotationAndPerspectiveTransform.m34 = 1.0 / perspective;
    rotationAndPerspectiveTransform = CATransform3DRotate(newTransform, degreesToRadians(10) , 0.0f, 1.0f, 0.0f);
    
    
    baseLayer.sublayerTransform = rotationAndPerspectiveTransform;