简体   繁体   中英

How to set UIView rotation by degrees

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 (eg 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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM