How to flip UIImage horizontally with Swift?

后端 未结 9 1926
余生分开走
余生分开走 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 01:01

    Swift 5

    If your use case requires saving the UIImage after transforming, it will need to be drawn into a new CGContext.

    extension UIImage {
      
      enum Axis {
        case horizontal, vertical
      }
      
      func flipped(_ axis: Axis) -> UIImage {
        let renderer = UIGraphicsImageRenderer(size: size)
        
        return renderer.image {
          let context = $0.cgContext
          context.translateBy(x: size.width / 2, y: size.height / 2)
          
          switch axis {
          case .horizontal:
            context.scaleBy(x: -1, y: 1)
          case .vertical:
            context.scaleBy(x: 1, y: -1)
          }
          
          context.translateBy(x: -size.width / 2, y: -size.height / 2)
          
          draw(at: .zero)
        }
      }
    }
    

提交回复
热议问题