Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

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

This comment has been minimized.

Copy link
Owner Author

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

This comment has been minimized.

Copy link

commented Feb 8, 2018

How to cache NSView filtered content?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.