UIImageview rotation is not working when using CGA

2019-09-17 11:57发布

问题:

I am rotating UIImageView with CGAffineTransformMakeRotation. Rotation is working fine. When I tried to get that image to another UIImageView , rotation is not working.

Coding 1:

@IBAction func rotateAcn(sender: UIButton) {

rotatingImageVw.transform = CGAffineTransformMakeRotation(0.22)

}

Output 1

Coding 2:

@IBAction func getRotatedImage(sender: UIButton) {

newImageView.image = rotatingImageVw.image

}

Output 2

I dont know why this happening? I need Output 2 as in Output 1 . Kindly guide me how to solve this?

回答1:

You are rotating the image view, not the image itself. You need to get the transform to the new image view as well.

newImageView.transform = rotatingImageVw.transform

If you want to rotate the image itself, and not the view, you can to use CIImage.applying(_:) and apply the transform on the image directly.



回答2:

Try this code: Tested in Swift 3

Note: You didn't post the proper code. So, I made one for you.

First VC:

import UIKit

extension Double {
func toRadians() -> CGFloat {
    return CGFloat(self * .pi / 180.0) }  }

extension UIImage {
func rotated(by degrees: Double) -> UIImage? {
    guard let cgImage = self.cgImage else { return nil }

    let transform = CGAffineTransform(rotationAngle: degrees.toRadians())
    var rect = CGRect(origin: .zero, size: self.size).applying(transform)
    rect.origin = .zero

    let renderer = UIGraphicsImageRenderer(size: rect.size)
    return renderer.image { renderContext in
        renderContext.cgContext.translateBy(x: rect.midX, y: rect.midY)
        renderContext.cgContext.rotate(by: degrees.toRadians())
        renderContext.cgContext.scaleBy(x: 1.0, y: -1.0)

        let drawRect = CGRect(origin: CGPoint(x: -self.size.width/2, y: -self.size.height/2), size: self.size)
        renderContext.cgContext.draw(cgImage, in: drawRect)
    }
   }
   }

class ViewController: UIViewController  {

@IBOutlet weak var imageView: UIImageView!


override func viewDidLoad() { }

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "passImageData" {
        let dvc = segue.destination as! viewtwo

       let rotatedImage = imageView.image?.rotated(by: 45) // You workout the angle ypu want
        dvc.newImage = rotatedImage

    } 

}

Second VC:

   import Foundation
   import UIKit

   class viewtwo: UIViewController {

   @IBOutlet weak var passedimage: UIImageView!

   var newImage: UIImage!

   override func viewDidLoad() {
   passedimage.image = newImage  
   }
   }