Search code examples
macoscore-graphicsretina-displaynswindowzooming

CGWindowListCreateImage yields blurred cgImage when zoomed


I'm developing a magnifying glass like application for mac. My goal is to be able to pinpoint individual pixels when zoomed in. I'm using this code in mouseMoved(with event: NSEvent):

let captureSize = self.frame.size.width / 9     //9 is the scale factor
 let screenFrame = (NSScreen.main()?.frame)!
 let x = floor(point.x) - floor(captureSize / 2)
    let y = screenFrame.size.height - floor(point.y) - floor(captureSize / 2)

    let windowID = CGWindowID(self.windowNumber)

cgImageExample = CGWindowListCreateImage(CGRect(x: x, y: y, width: captureSize, 
height: captureSize), CGWindowListOption.optionOnScreenBelowWindow, windowID, 
CGWindowImageOption.bestResolution)

The creation of the cgImage takes place in the CGWindowListCreateImage method. When I later draw this in an NSView, the result looks like this:

enter image description here

It looks blurred / like some anti-aliasing was applied during the creation of the cgImage. My goal is to get a razor sharp representation of each pixel. Can anyone point me in the right direction?


Solution

  • Ok, I figured it out. It was a matter of setting the interpolation quality to none on the drawing context:

     context.interpolationQuality = .none
    

    Result:

    enter image description here

    On request some more code:

    //get the context
    guard let context = NSGraphicsContext.current()?.cgContext else { return }
    
    //get the CGImage
    let image: CGImage = //pass the result from CGWindowListCreateImage call
    
    //draw
    context.draw(image, in: (CGRect of choice))