Reputation: 39
I'm trying to reflect accelerometer data in an iOS app by rotating a UIImageView object. Currently, I am rotating the object based on the difference between its current position reading and the previous position reading (e.g. if the accelerometer was at 90 degrees and is now at 80 degrees it will rotate the object -10 degrees). This method has issues though because there are unread changes in the accelerometer.
As such, I want to set the rotation of the UIImageView based on the degree orientation of the accelerometer. For example, if the accelerometer reads at 65 degrees, I want to set the orientation of the UIImageView object to 65 degrees. Is there a way to do this?
Furthermore, I would like for the rotation to be animated.
Here is my current code which rotates the image view object based on the change from the previous reading:
// UIImage view declaration
@IBOutlet weak var visualizer: UIImageView!
// Rotation code where 'deg' is the change in rotation from the previous reading
UIView.animate(withDuration: 1.0, delay: 0, options: .curveLinear, animations: { () -> Void in self.visualizer.transform = self.visualizer.transform.rotated(by: CGFloat(truncating: deg))})
Note that I would change another part of my code so that 'deg' would be the orientation of the accelerometer in degrees instead of the change in degrees.
Upvotes: 3
Views: 1696
Reputation: 2922
the rotation is based on Radian, so you just need to do the math
let radian = degree * CGFloat.pi / 180
to rotate object to n degree use CGAffineTransform
view.transform = CGAffineTransform(rotationAngle: (degree * CGFloat.pi / 180))
Upvotes: 3