4

I have been trying to perform a perspective transform on a UIView. I have been working from this example.

However, that example applies a rotation on the view as well as a perspective change. Is there a way to change the perspective of the view with no rotation? Something that might look like this:

enter image description here

I have been trying to remove the rotation, but when I do the perspective transform does not get applied. I can't find any examples out there that deal with just changing the perspective. Thanks in advance.

Community
  • 1
  • 1
tentmaking
  • 2,076
  • 4
  • 30
  • 53

2 Answers2

7

Just adding to David's answer: To get an output as in your image you have to rotate the view around the x-axis (the horizontal axis) so that the upper edge of the view rectangle appears "further away" from the viewer than the lower edge, e.g.

CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -200;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0f * M_PI / 180.0f, 1.0f, 0.0f, 0.0f);
layer.transform = rotationAndPerspectiveTransform;
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • @martinr I applied you technique and I don't get a perspective rotation. I have a flat one (the view seems to be same distance everywhere..) – Van Du Tran Jul 23 '15 at 20:13
  • @VanDuTran: Well, it is one of the components in a 3D transformation matrix :) I am not sure if I can explain it well, and in any case it is too complicated for a *comment*. You should find information about it in the Internet. – Martin R Jul 23 '15 at 20:17
  • I got it working now! However, I got a weird effect. I have a rectangle, where the anchor point is at the bottom middle. When I rotate the rectangle away, it looks fine. But when I rotate the rectangle towards me, the rectangle becomes so big it goes out of the screen.. it's like it's going to fall on top of my head! Do you know how to fix this effect? – Van Du Tran Jul 23 '15 at 20:24
  • Ok i found out. The smaller the .34, the less you'll have that effect. – Van Du Tran Jul 23 '15 at 20:29
0

Perspective won't be visible without any rotation relative to your view point. The perspective does still get applied even when you don't rotate but it won't be very visible.

One other transform that shows perspective is translating along Z which makes the view look like it is being scaled.

David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205