Search code examples
iosobjective-ctransformquartz-corecatransform3d

Achieve a trapezoid transform with CATransform3D


I'd like to change an UIView from:

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

To:

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

Forgive my ascii art. I mean to change a rectangular background to a trapezoid background, with:

  • same width
  • same right height

I tried this:

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;

The result is a trapezoid, but it has not the desired constraints.


Solution

  • 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.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