obtaining the rotation and size of a UIImageView b

2019-02-01 15:11发布

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 view, how can I calculate how much the image scaled and rotated?

I suppose that somehow these matrix contain these two informations. The problem is how to extract it...

any clues?

thanks for any help.

1条回答
Explosion°爆炸
2楼-- · 2019-02-01 16:07

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.

查看更多
登录 后发表回答