From 7edadc53dd66fac2cba3d6293a4121e123d88846 Mon Sep 17 00:00:00 2001 From: Mahshid Sharif Date: Wed, 22 Dec 2021 12:22:22 +0330 Subject: [PATCH] Add fixedOrientationToUp for UIImage --- .../UIImage/UIImage+Orientation.swift | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Sources/ExtensionKit/UIExtensions/UIImage/UIImage+Orientation.swift diff --git a/Sources/ExtensionKit/UIExtensions/UIImage/UIImage+Orientation.swift b/Sources/ExtensionKit/UIExtensions/UIImage/UIImage+Orientation.swift new file mode 100644 index 0000000..6c3ca6b --- /dev/null +++ b/Sources/ExtensionKit/UIExtensions/UIImage/UIImage+Orientation.swift @@ -0,0 +1,75 @@ +// +// UIImage+Orientation.swift +// +// +// Created by Mahshid Sharif on 12/22/21. +// + +import UIKit + +extension UIImage { + + func fixedOrientationToUp() -> UIImage? { + + guard imageOrientation != UIImage.Orientation.up else { + // This is default orientation, don't need to do anything + return self.copy() as? UIImage + } + + guard let cgImage = self.cgImage else { + // CGImage is not available + return nil + } + + guard let colorSpace = cgImage.colorSpace, let ctx = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { + return nil // Not able to create CGContext + } + + var transform: CGAffineTransform = CGAffineTransform.identity + + switch imageOrientation { + case .down, .downMirrored: + transform = transform.translatedBy(x: size.width, y: size.height) + transform = transform.rotated(by: CGFloat.pi) + case .left, .leftMirrored: + transform = transform.translatedBy(x: size.width, y: 0) + transform = transform.rotated(by: CGFloat.pi / 2.0) + case .right, .rightMirrored: + transform = transform.translatedBy(x: 0, y: size.height) + transform = transform.rotated(by: CGFloat.pi / -2.0) + case .up, .upMirrored: + break + @unknown default: + fatalError("Missing...") + break + } + + // Flip image one more time if needed to, this is to prevent flipped image + switch imageOrientation { + case .upMirrored, .downMirrored: + transform = transform.translatedBy(x: size.width, y: 0) + transform = transform.scaledBy(x: -1, y: 1) + case .leftMirrored, .rightMirrored: + transform = transform.translatedBy(x: size.height, y: 0) + transform = transform.scaledBy(x: -1, y: 1) + case .up, .down, .left, .right: + break + @unknown default: + fatalError("Missing...") + break + } + + ctx.concatenate(transform) + + switch imageOrientation { + case .left, .leftMirrored, .right, .rightMirrored: + ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.height, height: size.width)) + default: + ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) + break + } + + guard let newCGImage = ctx.makeImage() else { return nil } + return UIImage.init(cgImage: newCGImage, scale: 1, orientation: .up) + } +}