Skip to content

Instantly share code, notes, and snippets.

@ericdke
Last active March 3, 2023 13:47
Show Gist options
  • Save ericdke/1387b3b89938b6cf3732 to your computer and use it in GitHub Desktop.
Save ericdke/1387b3b89938b6cf3732 to your computer and use it in GitHub Desktop.
Resize NSImage
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!)!
}
@ysoftware
Copy link

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.

@PaulMcClernan
Copy link

PaulMcClernan commented Mar 3, 2023

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