0

I'm trying to rotate imageView and its UIImage together at the same time for better animation behavior it works well when I rotate for the first time, but when I rotate again the image doesn't change, what am I doing wrong?

let imageToRotate =  UIImageView()

@objc func rotateImageButtonTapped() {
    UIView.animate(withDuration: 0.3, animations: {
        let rotatedTransform = imageToRotate.transform.rotated(by: CGFloat.pi / 2)
        imageToRotate.transform = rotatedTransform
    })
   
    let image = imageToRotate.image

    DispatchQueue.global(qos: .userInteractive).async {
        let rotatedImage = image?.rotate(radians: .pi / 2)
           page.isRotated = .rotated(rotatedImage: rotatedImage?.jpegData(compressionQuality: 1) ?? Data())
    }
   
}
esraaed
  • 41
  • 1
  • 8
  • Why are you rotating both the image and the view? Just delete the DispatchQueue block and it should work fine. If it doesn't work, show where you call "rotateImageButtonTapped" in your code. – FelipeCruzV10 Jun 09 '21 at 14:30
  • `.rotate` is not a `UIImage` method... what is your `image?.rotate(radians: .pi / 2)` supposed to be doing? – DonMag Jun 09 '21 at 14:35
  • @DonMag I tried to rotate it using this https://stackoverflow.com/a/47402811/9872175 – esraaed Jun 09 '21 at 14:43
  • @FelipeCruzV10 I'm rotating both for better animation, also somewhere in my code I need only the UIImage and it's not accessible if I get it from my imageView the "rotateImageButtonTapped" is only a button – esraaed Jun 09 '21 at 14:45
  • If you rotate just the image view, the animation looks good. What do you mean with better animation? And I ask about the call of the function because I'm trying your code and it rotates good on each click... – FelipeCruzV10 Jun 09 '21 at 14:52
  • @FelipeCruzV10 thank you for your comment, that's the point it rotates good on each click, but when I rotate with double click let's say the image was 90 degree and I want it to be -90 the image is still the first rotation click which is 0 – esraaed Jun 09 '21 at 15:02
  • If you want double clicking, you have to target another function to manage it. I understand from what you've said, that a button calls the function on single click. – FelipeCruzV10 Jun 09 '21 at 15:14

1 Answers1

0

This code:

UIView.animate(withDuration: 0.3, animations: {
    let rotatedTransform = imageToRotate.transform.rotated(by: CGFloat.pi / 2)
    imageToRotate.transform = rotatedTransform
})

does NOT rotate the UIImage -- it rotates the image view.

So, when you then do:

let image = imageToRotate.image

you get the original image that you assigned to the image view.

DonMag
  • 69,424
  • 5
  • 50
  • 86