Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get scale and rotation angle from CGAffineTransform?

I want to get scale factor and rotation angle form view. I've already applied CGAffineTransform to that view.

like image 435
hmdeep Avatar asked Jul 18 '14 08:07

hmdeep


3 Answers

The current transformation of an UIView is stored in its transform property. This is a CGAffineTransform structure, you can read more about that here: https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGAffineTransform/Reference/reference.html

You can get the angle in radians from the transform like this:

CGFloat angle = atan2f(yourView.transform.b, yourView.transform.a);

If you want the angle in degrees you need to convert it like this:

angle = angle * (180 / M_PI);

Get the scale like this:

CGFloat scaleX = view.transform.a;
CGFloat scaleY = view.transform.d;
like image 98
Cornelius Avatar answered Nov 11 '22 13:11

Cornelius


I had the same problem, found this solution, but it only partially solved my problem. In fact the proposed solution for extracting the scale from the transform:

(all code in swift)

scaleX = view.transform.a
scaleY = view.transform.d

only works when the rotation is 0.

When the rotation is not 0 the transform.a and transform.d are influenced by the rotation. To get the proper values you can use

scaleX = sqrt(pow(transform.a, 2) + pow(transform.c, 2))
scaleY = sqrt(pow(transform.b, 2) + pow(transform.d, 2))

note that the result is always positive. If you are also interested in the sign of the scaling (the view is flipped), then the sign of the scaling is the sign of transform.a for x flip and transform.d for y flip. One way to inherit the sign.

scaleX = (transform.a/abs(transform.a)) * sqrt(pow(transform.a, 2) + pow(transform.c, 2))
scaleY = (transform.d/abs(transform.d)) * sqrt(pow(transform.b, 2) + pow(transform.d, 2))
like image 34
gabbo Avatar answered Nov 11 '22 11:11

gabbo


In Swift 3:

let rotation = atan2(view.transform.b, view.transform.a)

like image 5
cleverbit Avatar answered Nov 11 '22 12:11

cleverbit