Skip to content

Instantly share code, notes, and snippets.

@levicole
Last active April 25, 2016 05:04
Show Gist options
  • Save levicole/0a0688dd45564d1d34bd7f0a507a1bb2 to your computer and use it in GitHub Desktop.
Save levicole/0a0688dd45564d1d34bd7f0a507a1bb2 to your computer and use it in GitHub Desktop.
Draws Image in a target size. If it's aspect ratio won't fit in the size, it's cropped.
extension NSImage {
func drawInTargetSize(targetSize: NSSize) -> NSImage? {
let aspectRatio = max(targetSize.width/self.size.width, targetSize.height/self.size.height)
let newSize = NSSize(width: self.size.height * aspectRatio, height: self.size.height * aspectRatio)
var newRect = NSRect(origin: NSPoint(x: 0, y: 0), size: newSize)
let ctx = NSGraphicsContext()
guard let resizedImage = self.CGImageForProposedRect(&newRect, context: ctx, hints: nil) else { return nil }
let yOffset = (newSize.height > targetSize.height) ? floor((newSize.height - targetSize.height)/2.0) : 0
let xOffset = (newSize.width > targetSize.width) ? floor((newSize.width - targetSize.width)/2.0) : 0
guard let croppedImage = CGImageCreateWithImageInRect(resizedImage, CGRect(x: xOffset, y: yOffset, width: targetSize.width, height: targetSize.height)) else { return nil }
return NSImage(CGImage: croppedImage, size: targetSize)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment