Resizing an Image by preserving aspect ratio in swift

I have the following extension to resize an image.



extension NSImage {
func resizeImage(width: CGFloat, _ height: CGFloat) -> NSImage {
let img = NSImage(size: CGSize(width:width, height:height))
img.lockFocus()
let ctx = NSGraphicsContext.current()
ctx?.imageInterpolation = .high
self.draw(in: NSMakeRect(0, 0, width, height), from: NSMakeRect(0, 0, size.width, size.height), operation: .copy, fraction: 1)
img.unlockFocus()
return img
}
}


On resizing the aspect ratio is not preserved.


How can I modify the code to preserve aspect ratio?



Please advice.

You need to compute a single scale factor to apply to both the width and height. For example, something like this:


let theWidthScaleFactor = targetImageWidth / sourceImageWidth
let theHeightScaleFactor = targetImageHeight / sourceImageHeight
let theScaleFactor = min(theWidthScaleFactor, theHeightScaleFactor)


Here, you take the samller of the two scale factors and use that to compute the final image's dimensions:


let theWidth = targetImageWidth * theScaleFactor
let theHeight = targetImageHeight * theScaleFactor

Thanks.But i'm new to the language.In c# we do something like this stackoverflow.com/a/2001692/848968


Can you please update the extension.

Sorry, but I (and you'll find many here) won't write code for others that can just be cut-and-pasted. At least to such basic functions. I outlined the premise of what you need to do and you should really adapt that to your code. It's a great learning exercise.

okay.thanks... will check it out.

Please see the code which i have updated.Is this correct?


extension NSImage {
func resizeImage(width: CGFloat, _ height: CGFloat,owidth:CGFloat,oheight:CGFloat) -> NSImage {
let theWidthScaleFactor = width / owidth
let theHeightScaleFactor = height / oheight
let theScaleFactor = min(theWidthScaleFactor, theHeightScaleFactor)
let theWidth = width * theScaleFactor
let theHeight = height * theScaleFactor
let img = NSImage(size: CGSize(width:theWidth, height:theHeight))
img.lockFocus()
let ctx = NSGraphicsContext.current()
ctx?.imageInterpolation = .high
self.draw(in: NSMakeRect(0, 0, width, height), from: NSMakeRect(0, 0, size.width, size.height), operation: .copy, fraction: 1)
img.unlockFocus()
return img
}
}
Resizing an Image by preserving aspect ratio in swift
 
 
Q