How to flip UIImage horizontally with Swift?

后端 未结 9 1885
余生分开走
余生分开走 2020-12-13 00:16

The solution to do UIImage flipping is with the Objective-C code:

[UIImage imageWithCGImage:img.CGImage scale:1.0 orientation: UIImageOrientationDownMirrored         


        
9条回答
  •  伪装坚强ぢ
    2020-12-13 00:46

    There is couple of similar questions on SO. And I believe it's worth to post solution using CoreImage here too.

    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 }
    
            // Flip the image itself
            let flip = CGAffineTransform(scaleX: 1, y: -1)
            let outputImage = inputImage.transformed(by: flip)
    
            // Create CGImage first
            guard let cgImage = CIContext().createCGImage(outputImage, from: outputImage.extent) 
                else { return self }
    
            // Create output UIImage from CGImage
            return UIImage(cgImage: cgImage)
        }
    }
    

提交回复
热议问题