1

I have the current code that's working for ios.But as many of you know UIKit isn't in Mac OSX apps.How could I save a nsimage with the subviews I added

private func screenShotMethod() -> NSImage? {

    //Create the UIImage
    NSGraphicsBeginImageContext(self.pickedImge.frame.size)
    self.pickedImge.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = NSGraphicsGetImageFromCurrentImageContext()
    NSGraphicsEndImageContext()

    //Save it to the camera roll
    UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
    return image!
}
j4awesome
  • 57
  • 10

1 Answers1

0

I've ported this answer from code I found in this very related question.

class CustomView : NSView {

    func saveAScreenShotOfThisViewSomewhere() -> Void {
        self.lockFocus()
        let rep = NSBitmapImageRep(focusedViewRect: self.bounds)
        self.unlockFocus()
        if let data = rep?.tiffRepresentation {
            do {
                try data.write(to: URL(string:"/tmp/someplace.tiff")!, options: Data.WritingOptions.atomic)
            } catch {
                Swift.print("error in writing -> \(error.localizedDescription)")
            }
        }
    }
}

You can also use

    if let data = rep?.representation(using: .JPEG, properties: [String : Any]) {

    }

where representation includes BMP, GIF, JPEG, PNG, TIFF, etc.

I hope this helps!

Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • That's great but i'm using a NSImage not a NSView.The function above is taking a screenshot of a UIImage with the subviews – j4awesome Jan 18 '17 at 17:56
  • You can also use the code above to subclass `NSImageView` so you can save both the image contained by the image view as well as its subclasses. Did I misunderstand your question? – Michael Dautermann Jan 19 '17 at 10:45