Rotate UIImage in swift

后端 未结 8 1595
一整个雨季
一整个雨季 2021-02-04 10:35

I want to rotate UIImage in clockwise direction. But my current code do not perform function accurate some time it rotate and some time its skip rotation. I want my UIImage will

8条回答
  •  遇见更好的自我
    2021-02-04 11:02

    I believe it's worth to post solution using CoreImage. It's just couple of lines and it works great for me.

    Please note: when getting final UIImage, it's necessary to convert to CGImage first to respect extent of CIImage

    extension UIImage {
        func imageRotated(by degrees: CGFloat) -> UIImage {
    
            let orientation = CGImagePropertyOrientation(imageOrientation)
            // Create CIImage respecting image's orientation 
            guard let inputImage = CIImage(image: self)?.oriented(orientation) 
                else { return self }
    
            // Rotate the image itself
            let rotation = CGAffineTransform(rotationAngle: (degrees * CGFloat.pi / 180))
            let outputImage = inputImage.transformed(by: rotation)
    
            // Create CGImage first
            guard let cgImage = CIContext().createCGImage(outputImage, from: outputImage.extent) 
                else { return self }
    
            // Create output UIImage from CGImage
            return UIImage(cgImage: cgImage)
        }
    }
    

提交回复
热议问题