NSView dataWithPDF inside rect but with background view

641 views Asked by At

I wan´t to take a screenshot of a NSView but when I do this, I get an image without the background. All the subviews are show, but not the background. I use this code:

if let image = NSImage(data: background.dataWithPDF(inside: background.bounds)) {
    let imageView = NSImageView(image: image)
    imageView.imageScaling = .scaleProportionallyUpOrDown
    return NSImageView(image: image)
}

I thought, ok when I get only the subviews, then I will make a screenshot of the superview and I thried the following:

if let superview = background.superview, let image = NSImage(data: superview.dataWithPDF(inside: background.frame)) {
    let imageView = NSImageView(image: image)
    imageView.imageScaling = .scaleProportionallyUpOrDown
    return NSImageView(image: image)
}

But I get the same result. Even if I set the background color of my background view I don´t get an image without transparent background.

How can I resolve this?

thank you

Artur

2

There are 2 answers

0
Artur Hellmann On BEST ANSWER

I got an Answer:

background.lockFocus()
if let rep = NSBitmapImageRep(focusedViewRect: background.bounds){

    let img = NSImage(size: background.bounds.size)
    img.addRepresentation(rep)

    return NSImageView(image: img)
}
background.unlockFocus()
0
Adam Dahan On

You could have converted the views backing layer.backgroundColor to an image. Then assign the image to a backing image view that sits in the 0th index of your views heirarchy and use the method dataWithPDF -> that will successfully capture a background.