Search code examples
objective-cswiftuiviewtransformcalayer

Convert UIView transform to CALayer


I have UIView which I apply transform to. I'm trying to understand how to fetch the rotation of the UIView and apply it to the CALayer. If I'm printing the UIView transform I get this:

CGAffineTransform(a: 0.977750351365919, b: -0.209771900891948, c: 0.209771900891948, d: 0.977750351365919, tx: 0.0, ty: 0.0)

Though, I can't understand how to apply the rotation transform the the CALayer.

layer.transform

expecting to get CATransform3D.


Solution

  • What you expect to have happen does happen. I ran this code:

    self.v.transform = CGAffineTransformMakeRotation(0.5)
    

    And later this code:

    let t = self.v.layer.transform
    print(t)
    

    It printed this:

    CATransform3D(m11: 0.877582561890373, m12: 0.479425538604203, m13: 0.0, m14: 0.0, m21: -0.479425538604203, m22: 0.877582561890373, m23: 0.0, m24: 0.0, m31: 0.0, m32: 0.0, m33: 1.0, m34: 0.0, m41: 0.0, m42: 0.0, m43: 0.0, m44: 1.0)

    That is indeed the CATransform3D form of the affine transform originally applied to the view. You could now apply this same transform to some other layer if desired.

    Note too that in the special case where the transform to be applied to the layer is an affine transform, you can apply it directly as an affine transform (using the setAffineTransform: method). So there is actually no need to fetch the view's layer's transform; you can apply the view's affine transform directly to another layer.