I'm building a Mac OS app in SwiftUI. I have a use case where I must crop part of the image (which is a screenshot) and ensure the cropped part is at least 320x240 and match the aspect ratio if it exceeds.
I have below code so far:
func fitImageInRect(_ original: NSImage, rect: CGRect) -> NSImage {
var originalRect = CGRect(x: 0, y: 0, width: original.size.width, height: original.size.height)
var width = 0.0, height = 0.0
if rect.width > rect.height {
width = rect.width
if width > 320 {
let ratio = width / 320
height = 240 * ratio
} else {
width = 320
height = 240
}
} else {
height = rect.height
if height > 240 {
let ratio = height / 240
width = 320 * ratio
} else {
width = 320
height = 240
}
}
var originX = rect.origin.x
var originY = rect.origin.y
if originX > (originalRect.width - 320) {
originX = originalRect.width - 320
}
if originY > (originalRect.height - 240) {
originY = originalRect.height - 240
}
let thumbnailRect = CGRect(x: Int(originX), y: Int(originY), width: Int(width), height: Int(height))
guard let ref = original.cgImage(forProposedRect: &originalRect, context: nil, hints: nil) else { return original }
let cropped = ref.cropping(to: thumbnailRect)
return NSImage(cgImage: cropped!, size: NSSize(width: width, height: height))
}
The goal is as follows:
- If the
rect
size is 150x50, then the cropped photo be 320x240 withrect
at center of it. - If the
rect
size is 640x50, then the cropped photo be 640x480 withrect
at center of it.
But somehow, the code is behaving otherwise. The final output is seemingly from a vertically flipped thumbnailRect
and I can't figure out why.