objective-cmacosnsimagensimageviewmacos-mojave

macOS Mojave - NSReadPixel is not working


I have subclassed NSImageView to override mouseDown method to get the colour of clicked point and so far it was working fine on all OS versions (up to 10.13.x) but on 10.14 this doesn't seems to be working and I am always getting null colour when using NSReadPixel. Below is my code of mouseDown method.

- (void)mouseDown:(NSEvent *)theEvent{
if(!self.image)
    return;
NSPoint clickedPoint = theEvent.locationInWindow;
NSPoint pointInDocumentView = [self convertPoint:clickedPoint fromView:nil];
[self lockFocus];
NSColor* colorAtClickedPoint = NSReadPixel(pointInDocumentView);
[self unlockFocus];
if(colorAtClickedPoint){
    if(self.delegate){
       [self.delegate colourCodeDidChange:colorAtClickedPoint];
    }
}

}

Please help.


Solution

  • This method is deprecated in 10.14. You may use other methods like the following. Hope you have no problem with the answer.

    - (void)mouseDown:(NSEvent *)theEvent{
                if(!self.image)
                    return;
                NSPoint clickedPoint = theEvent.locationInWindow;
    
                NSPoint pointInDocumentView = [self convertPoint:clickedPoint fromView:nil];
                NSBitmapImageRep * bitmapImageRep = [self bitmapImageRepForCachingDisplayInRect:self.bounds];
                [self cacheDisplayInRect:self.bounds toBitmapImageRep:bitmapImageRep];
                [self lockFocus];
                  NSColor* colorAtClickedPoint  =  [bitmapImageRep colorAtX:pointInDocumentView.x y:pointInDocumentView.y];
    
                [self unlockFocus];
                if(colorAtClickedPoint){
                    if(self.delegate){
                        [self.delegate colourCodeDidChange:colorAtClickedPoint];
                    }
                }
    
            }