Last active
April 25, 2016 05:04
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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