使用CATransform3D实现梯形变换

时间:2015-07-17 08:58:55

标签: ios objective-c transform quartz-core catransform3d

我想改变一个UIView:

         o---o
         |   |
         |   |
         |   |
         |   |
         |   |
         o---o

要:

            /o
           / |
         o/  |
         |   |
         o\  |
           \ |
            \o

原谅我的ascii艺术。我的意思是将矩形背景更改为梯形背景,其中包括:

  • 相同宽度
  • 同样正确的高度

我试过了:

CATransform3D sublayerTransform = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, .005, 0, 0, 0, 1 };
self.backgroundView.layer.superlayer.sublayerTransform = sublayerTransform;
CATransform3D layerTransform = CATransform3DMakeRotation(M_PI/4., 0, 1, 0);
self.backgroundView.layer.transform = layerTransform;

结果是一个梯形,但它没有所需的约束。

2 个答案:

答案 0 :(得分:2)

看看CATrasnsform3D矩阵,在你的情况下,你真的只需要设置.m34。

请记住,CATransform3DRotate将弧度视为其中一个参数,其定义如下;

  float Degrees2Radians(float degrees) { return degrees * M_PI / 180; }

尝试以下方法;

  CATransform3D transform = CATransform3DIdentity;
  transform.m34 = -1.0f /450.0f; 

  // set y to  negative for effect on left(as in your diagram), positive for effect on right
  transform = CATransform3DRotate(transform, Degrees2Radians(45) , 0.0f, -1.0f, 0.0f);

  // you'll need to do this translate to shift the layer to compensate for  the rotation
  transform = CATransform3DTranslate(transform, -70.0f, 0.0f, -50.0f);

然后显然将目标图层变换为上面的变换

答案 1 :(得分:0)

我能够使用AGGeometryKit轻松实现正确的CATransform3D。

#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.y += 10; // shift top left y-value with 10 pixels
quad.bl.y -= 10; // shift bottom left y-value with 10 pixels
view.layer.quadrilateral = quad; // the quad is converted to CATransform3D and applied