1

I'm trying to add perspective to a view by using CATransform3D. Currently, this is what I'm getting:

enter image description here

And this is what I wanna get:

enter image description here

I'm having a hard time doing that. I'm completely lost here. Here's my code:

CATransform3D t = CATransform3DIdentity;
    t.m11 = 0.8;
    t.m21 = 0.1; 
    t.m31 = -0.1; 
    t.m41 = 0.1;
    [[viewWindow layer] setTransform:t];
Fernando Valente
  • 1,096
  • 1
  • 8
  • 30

2 Answers2

2

Matrix element .m34 is responsible for perspective. It's not discussed much in the documentation, so you'll have to toy with it. This answer talks a little bit about how to use it: https://stackoverflow.com/a/7596326/1228525

To actually see the effects of that matrix you need to do two things: 1. Apply that perspective matrix to the parent view's sublayer transform 2. Rotate the child view (the one on which you want perspective) - otherwise it will remain flat and you won't be able to tell it now has a 3D perspective.

The numbers are arbitrary, make them whatever looks best:

CATransform3D t = CATransform3DIdentity;
t.m34 = .005;
parentView.layer.sublayerTransform. = t;
childview.layer.transform = CATransform3DMakeRotation(45,1,0,0); 

The perspective will look different depending on where the child is in the parent view. If the child is in the center of the parent it will be like you are looking at the child view in 3D straight on. The further from the center it is, the more it will be like you are viewing from a glancing angle.

This is what I got using the above code and centering the child view: (apparently I'm not allowed to post pictures since I'm new, so you'll have to see the link) https://i.stack.imgur.com/BiYCS.png

It's very hard to tell what you're going for based on those pictures; a bit more explanation might be helpful if my answer isn't what you want. From what I can tell from the picture, the bottom one isn't perspective...

Community
  • 1
  • 1
Hooper
  • 195
  • 13
  • Do you mean `CATransfrom3DMakeRotation(45/180*2*3.1416, 1, 0, 0)`? The value of the first parameter should be in radian. – ZhangChn Mar 31 '12 at 07:03
  • Nope. As I said, the numbers are arbitrary, make them whatever you want. – Hooper Mar 31 '12 at 19:39
0

I was able to easily achieve the right CATransform3D using AGGeometryKit.

#import <AGGeometryKit/AGGeometryKit.h>

UIView *view = ...; // create a view

// setting anchorPoint to zero
view.layer.anchorPoint = CGPointZero;
view.layer.transform = CATransform3DMakeTranslation(-view.layer.bounds.size.width * .5, -view.layer.bounds.size.height * .5, 0);

// setting a trapezoid transform
AGKQuad quad = view.layer.quadrilateral;
quad.tl.x -= 10; // shift top left x-value with 10 pixels
view.layer.quadrilateral = quad; // the quad is converted to CATransform3D and applied
Cœur
  • 37,241
  • 25
  • 195
  • 267