How to flip UIImage horizontally with Swift?

后端 未结 9 1877
余生分开走
余生分开走 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)
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-13 01:04

    For me the simplest way was to use the .withHorizontallyFlippedOrientation() instance method of UIImage as follows:

    let flippedImage = straightImage.withHorizontallyFlippedOrientation()

    Simple one-liners always make me happy :)

    0 讨论(0)
  • 2020-12-13 01:05

    Swift 4

    YOURIMAGEVIEW.transform = CGAffineTransform(scaleX: -1, y: 1)
    
    0 讨论(0)
提交回复
热议问题