1

I am using UIRotationGestureRecognizer to rotate an image. I would like to convert the angle of rotation from Radians to Degrees becuase I can think better in degrees. I found a solution on stack and other sources but for some reason the solution does not seem to work

For example, when I rotate the image counter clockwise about 45 degrees am getting a degree value of approximately -0.15 from the formula???

@objc func handleImageRotation(sender: 
UIRotationGestureRecognizer){
    guard sender.view != nil else{return}

    if sender.state == .began || sender.state == .changed {
        // rotation enacted
        imageView.transform = imageView.transform.rotated(by: sender.rotation)
        rotationAngleRads = sender.rotation
        rotationAngleDegs = rad2Deg(radians: rotationAngleRads)
        print("Degrees: \(rotationAngleDegs!)")

        sender.rotation = 0
     }
}


 // Convert Radians to Degress
private func rad2Deg(radians: CGFloat) -> Double{

    let angle = Double(radians) * (180 / .pi)
    return Double(angle)
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
jamesMcKey
  • 481
  • 5
  • 28
  • You could check this: https://stackoverflow.com/questions/2051811/iphone-sdk-cgaffinetransform-getting-the-angle-of-rotation-of-an-object – Andreas Oetjen Jul 11 '19 at 18:21

1 Answers1

1

Your main issue is that you are resetting the gesture's rotation property. You should not do that. From the documentation:

The rotation value is a single value that varies over time. It is not the delta value from the last time that the rotation was reported. Apply the rotation value to the state of the view when the gesture is first recognized—do not concatenate the value each time the handler is called.

So remove the sender.rotation = 0 line.

As a result of that, you need to fix how you apply the transform to the image view.

Replace:

imageView.transform = imageView.transform.rotated(by: sender.rotation)

with:

imageView.transform = CGAffineTransform(rotatationAngle: sender.rotation)

That applies the full rotation instead of trying to increment the current rotation.

rmaddy
  • 314,917
  • 42
  • 532
  • 579