Search code examples
iosobjective-ccgaffinetransformcatransform3d

CATransform3D no perspective


I have done this before but I somehow don't get this to work. I have googled a bit but none of the answers I have found solve it.

I am just trying to add a small view to my self.view and would like to rotate this added subview on its y-axis with perspective.

Here is the code:

UIView *rotatingView = [[UIView alloc] initWithFrame:(CGRect){{40.0f, 50.0f}, 50.0f, 50.0f}];
rotatingView.backgroundColor = [UIColor lightGrayColor];
CATransform3D transform = CATransform3DIdentity;
transform.m34 = 1.0 / -500.0;

transform = CATransform3DMakeRotation(DEGREES_RADIANS(20.0f), 0.0f, 1.0f, 0.0f);
rotatingView.layer.transform = transform;
[self.view addSubview:rotatingView];

It is plain simple. But there is absolutely no perspective whatsoever. I expect to see a "skewed" view so that it gives the perspective that it is rotated on the y-axis, but to no avail.

I have even tried setting zPosition and the anchorPoint but none helps.

I have a feeling that I am just missing just something very simple. How I did it before has slipped out of my mind.


Solution

  • You are overwriting the transform that has perspective with the rotation transform

    // Define the "transform" variable here
    CATransform3D transform = CATransform3DIdentity;
    transform.m34 = 1.0 / -500.0;
    
    // assign a new transform to it here
    transform = CATransform3DMakeRotation(DEGREES_RADIANS(20.0f), 0.0f, 1.0f, 0.0f);
    

    You should probably be using CATransform3DRotate instead:

    transform = CATransform3DRotate(transform, DEGREES_RADIANS(20.0f), 0.0f, 1.0f, 0.0f);