obtaining the rotation and size of a UIImageView based on its transformation matrices

后端 未结 1 590
情深已故
情深已故 2020-12-25 09:07

If I have the original transform matrix of a rectangular UIImageView and this image is scaled and rotated and by the end I can read the final transform matrix of this same v

相关标签:
1条回答
  • 2020-12-25 09:35

    A little bit of matrix algebra and trigonometric identities can help you solve this.

    We'll work forward to generate a matrix that scales and rotates, and then use that to figure out how to extract the scale factors and rotations analytically.

    A scaling matrix to scale by Sx (in the X axis) and Sy (in the Y axis) looks like this:

    ⎡Sx  0 ⎤
    ⎣0   Sy⎦
    

    A matrix to rotate clockwise by R radians looks like this:

    ⎡cos(R)   sin(R)⎤
    ⎣-sin(R)  cos(R)⎦
    

    Using standard matrix multiplication, the combined scaling and rotation matrix will look like this:

    ⎡Sx.cos(R)   Sx.sin(R)⎤
    ⎣-Sy.sin(R)  Sy.cos(R)⎦
    

    Note that linear transformations could also include shearing or other transformations, but I'll assume for this question that only rotation and scaling have occurred (if a shear transform is in the matrix, you will get inconsistent results from following the algebra here; but the same approach can be used to determine an analytical solution).

    A CGAffineTransform has four members a, b, c, d, corresponding to the 2-dimensional matrix:

    ⎡a  b⎤
    ⎣c  d⎦
    

    Now we want to extract from this matrix the values of Sx, Sy, and R. We can use a simple trigonometric identity here:

    tan(A) = sin(A) / cos(A)
    

    We can use this with the first row of the matrix to conclude that:

    tan(R) = Sx.sin(R) / Sx.cos(R) = b / a    and therefore    R = atan(b / a)
    

    And now we know R, we can extract the scale factors by using the main diagonal:

    a = Sx.cos(R)    and therefore    Sx = a / cos(R)
    d = Sy.cos(R)    and therefore    Sy = d / cos(R)
    

    So you now know Sx, Sy, and R.

    0 讨论(0)
提交回复
热议问题