Last active
March 3, 2023 13:47
-
-
Save ericdke/1387b3b89938b6cf3732 to your computer and use it in GitHub Desktop.
Resize NSImage
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
func resize(image: NSImage, w: Int, h: Int) -> NSImage { | |
var destSize = NSMakeSize(CGFloat(w), CGFloat(h)) | |
var newImage = NSImage(size: destSize) | |
newImage.lockFocus() | |
image.drawInRect(NSMakeRect(0, 0, destSize.width, destSize.height), fromRect: NSMakeRect(0, 0, image.size.width, image.size.height), operation: NSCompositingOperation.CompositeSourceOver, fraction: CGFloat(1)) | |
newImage.unlockFocus() | |
newImage.size = destSize | |
return NSImage(data: newImage.TIFFRepresentation!)! | |
} |
I input 200x200 and it returns image of size 400x400.
Just to clarify for anyone here looking for the reason for this (as opposed to Swift code solution),
this is due to newer 'Retina' displays which have double the pixel density (144px per inch, vs. older screen resolution of 72px), there may be higher screen resolutions in the future with 4K, 6K, and 8K screens becoming more widely available.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't work right.
I input 200x200 and it returns image of size 400x400.
https://gist.github.com/raphaelhanneken/cb924aa280f4b9dbb480
Found a better solution here.