Getting co-ordinates of bitmap on mouseDown in NSImageView

327 views Asked by At

I am working on an app where I display unsupported (by XCode) file format). So I've subclassed NSBitmapImageRep to display it in a subclass of NSImaageView. I've set it up to be proportionally scallable (up or down). Now I need to add a possibility to get coordinates of pixel in a bitmap. So I've ovveride mouseDown: method:

- (void)mouseDown:(NSEvent *)theEvent
{
    NSLog(@"mouseDown: %ld", [theEvent clickCount]);
    NSPoint point = [theEvent locationInWindow];
    NSLog(@"point x: %f and y: %f", point.x, point.y);    
}

After getting NSPoint I should try to convert it to co-ordinates of a bitmap BUT first I have no idea How to solve the problem that locationInWindow returns NSPoint of a NSImageView, not of the bitmap which is ussually smaller and has unused margins in NSImageView, but I can click on the margin and mouseDown event returns me NSPoint in that margin. Do you have any idea what I shoud do?

1

There are 1 answers

3
user1118321 On BEST ANSWER

You need a view to image matrix. It's a matrix that maps view coordinates to image coordinates. Usually it will be a combination of scale and translation.

First you need to decide if you want to scale the image so that it is entirely visible, but fits within the window, or so that it entirely fills the window. (Or there are other options, like always showing the image at 1:1 regardless of the size of the window.) That will determine the scale of the image.

Next you need to decide how to position the scaled image. If you scale it to always fit in the window, and there's padding, do you favor the left and top of the window, or always try to center it? IF it's scaled to always fill the window, is it centered vertically or horizontally in the window? Or is the origin of the image always displayed in the lower left of the window?

Once you've figured out the scale and translate, you can compose a single matrix from the 2 of them. Once you've done that, get the inverse of the matrix, and that will transform your view coordinates into image pixels.