Skip to content

Instantly share code, notes, and snippets.

@kaishin
Created January 10, 2016 14:29
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kaishin/d4df8fc6c701ca635e25 to your computer and use it in GitHub Desktop.
Save kaishin/d4df8fc6c701ca635e25 to your computer and use it in GitHub Desktop.
NSView Snapshot
extension NSView {
var snapshot: NSImage {
guard let bitmapRep = bitmapImageRepForCachingDisplayInRect(bounds) else { return NSImage() }
bitmapRep.size = bounds.size
cacheDisplayInRect(bounds, toBitmapImageRep: bitmapRep)
let image = NSImage(size: bounds.size)
image.addRepresentation(bitmapRep)
return image
}
}
@kaishin
Copy link
Author

kaishin commented Jan 10, 2016

Not sure how to get a retina-scale (@2x) snapshot here. Tried messing with the different sizes but nothing worked...

@kaishin
Copy link
Author

kaishin commented Jan 10, 2016

Figured it out. You need to change the bitmap representation properties (size in this instance) after setting it as a represenation of our target image. Props to @robrix for pointing me in the right direction!

extension NSView {
  var snapshot: NSImage {
    guard let bitmapRep = bitmapImageRepForCachingDisplayInRect(bounds) else { return NSImage() }
    cacheDisplayInRect(bounds, toBitmapImageRep: bitmapRep)
    let image = NSImage()
    image.addRepresentation(bitmapRep)
    bitmapRep.size = bounds.size.doubleScale()
    return image
  }
}

extension CGSize {
  func doubleScale() -> CGSize {
    return CGSize(width: width * 2, height: height * 2)
  }
}

@hllovesgithub
Copy link

How to cache NSView filtered content?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment