How to rotate an image 90 degrees on iOS?

后端 未结 14 1912
野的像风
野的像风 2020-11-29 00:55

What I want to do is take a snapshot from my camera , send it to a server and then the server sends me back the image on a viewController. If the image is in portrait mode t

14条回答
  •  悲&欢浪女
    2020-11-29 01:45

    If you are looking to save image then you need to rotate picture context not the view. I have used provided examples above but they did not work well when centering the image. So I have enhanced and fixed as follows :

    func imageRotatedByDegrees(deg degrees: CGFloat) -> UIImage {
    
        UIGraphicsBeginImageContext(CGSize(width: self.size.height, height: self.size.width))
    
        let bitmap: CGContext = UIGraphicsGetCurrentContext()!
    
        // Move the origin to the middle of the image so we will rotate and scale around the center.
        bitmap.translateBy(x: self.size.width / 2, y: self.size.height / 2)
    
        // Rotate the image context
        bitmap.rotate(by: (degrees * CGFloat(Double.pi / 180)))
    
        // Now, draw the rotated/scaled image into the context
        bitmap.scaleBy(x: 1.0, y: -1.0)
    
        let origin = CGPoint(x: -self.size.height / 2, y: -self.size.width / 2)
    
        bitmap.draw(self.cgImage!, in: CGRect(origin: origin, size: CGSize(width: self.size.width, height: self.size.height)))
    
        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    
        UIGraphicsEndImageContext()
    
        return newImage
    }
    

提交回复
热议问题