Skip to content

Commit

Permalink
fix crop
Browse files Browse the repository at this point in the history
  • Loading branch information
tsuzukihashi committed Dec 28, 2021
1 parent cfc2cf6 commit 8c62d8f
Showing 1 changed file with 26 additions and 3 deletions.
29 changes: 26 additions & 3 deletions Sources/ImagePickerSwiftUI/UIImageExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,39 @@ public extension UIImage {
func croppingToSquare() -> UIImage? {
guard let cgImage = cgImage else { return nil }
let resizeSize = min(cgImage.width, cgImage.height)
let cropCGImage = cgImage.cropping(
return cropping(
to: .init(
x: (cgImage.width - resizeSize) / 2,
y: (cgImage.height - resizeSize) / 2,
width: resizeSize,
height: resizeSize
)
)
}

func cropping(to rect: CGRect) -> UIImage? {
let croppingRect: CGRect = imageOrientation.isLandscape ? rect.switched : rect
guard let cgImage: CGImage = self.cgImage?.cropping(to: croppingRect) else { return nil }
let cropped: UIImage = UIImage(cgImage: cgImage, scale: scale, orientation: imageOrientation)
return cropped
}
}

extension CGRect {
var switched: CGRect {
return CGRect(x: minY, y: minX, width: height, height: width)
}
}

guard let cropCGImage = cropCGImage else { return nil }
return UIImage(cgImage: cropCGImage, scale: 0, orientation: imageOrientation)
extension UIImage.Orientation {
var isLandscape: Bool {
switch self {
case .up, .down, .upMirrored, .downMirrored:
return false
case .left, .right, .leftMirrored, .rightMirrored:
return true
@unknown default:
fatalError()
}
}
}

0 comments on commit 8c62d8f

Please sign in to comment.