How do you get the current angle/rotation/radian a UIView has?
Asked
Active
Viewed 2.9k times
59
-
I know it should be like myView.transformation something.. but hooow? – Hjalmar Apr 22 '11 at 11:22
-
1possible duplicate of [iphone sdk CGAffineTransform getting the angle of rotation of an object](http://stackoverflow.com/questions/2051811/iphone-sdk-cgaffinetransform-getting-the-angle-of-rotation-of-an-object) – Abizern Jul 05 '11 at 09:34
-
@Abizern not really, He's asking for how to do it with CGAffineTransform. Which you can't. – Hjalmar Apr 15 '14 at 07:28
7 Answers
115
You can do it this way...
CGFloat radians = atan2f(yourView.transform.b, yourView.transform.a);
CGFloat degrees = radians * (180 / M_PI);

Krishnabhadra
- 34,169
- 30
- 118
- 167
-
3I would vote you up for 10! I just happened to come across this post and had to laugh as I totally forgot about inverse trigonometry! Just as I was starting to feel that my school education all those years ago was a waste :D – Adrian Sluyters Jan 13 '16 at 10:35
17
Swift:
// Note the type reference as Swift is now string Strict
let radians:Double = atan2( Double(yourView.transform.b), Double(yourView.transform.a))
let degrees:CGFloat = radians * (CGFloat(180) / CGFloat(M_PI) )

marcospereira
- 12,045
- 3
- 46
- 52

Peter Kreinz
- 7,979
- 1
- 64
- 49
7
A lot of the other answers reference atan2f
, but given that we're operating on CGFloat
s, we can just use atan2
and skip the unnecessary intermediate cast:
Swift 4:
let radians = atan2(yourView.transform.b, yourView.transform.a)
let degrees = radians * 180 / .pi

Dan Loewenherz
- 10,879
- 7
- 50
- 81
6
For Swift 3, you could use the following code:
let radians:Float = atan2f(Float(view.transform.b), Float(view.transform.a))
let degrees:Float = radians * Float(180 / M_PI)

Frits
- 7,341
- 10
- 42
- 60

Rakesh Yembaram
- 433
- 4
- 7
6
//For Swift 3: M_PI is depreciated now Use Double.pi
let radians = atan2f(Float(yourView.transform.b), Float(yourView.transform.a));
let degrees = radians * Float(180 / Double.pi)
//For Swift 4:
let radians = atan2(yourView.transform.b, yourView.transform.a)
let degrees = radians * 180 / .pi

Rohit Sisodia
- 895
- 12
- 13
0
Using extensions:
extension UIView {
var rotation: Float {
let radians:Float = atan2f(Float(transform.b), Float(transform.a))
return radians * Float(180 / M_PI)
}
}
Usage:
let view = UIView()
print(view.rotation)

Hossein
- 797
- 1
- 8
- 24