Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting bounds of an NSImage within an NSImageView

I've got an NSImageView that takes up the full extent of a window. There's no border to the image view, and its set to display in the lower left. So this means that the origin of the view matches the origin of actual image, no matter how the window is resized.

Also, the image is much larger than what I can reasonably fit at full scale on the screen. So I also have the imageview set to proportionally scale down the size of the image. However, I can't seem to find this scale factor anywhere.

My ultimate goal is to map a mouse down event into actual image coordinates. To do this, I think I need one more piece of information...how big the displayed NSImage actually is.

If I look at the [imageView bounds], I get the bounding rectangle of the image view, which generally will be larger than the image.

like image 472
wrjohns Avatar asked Jul 29 '12 18:07

wrjohns


1 Answers

I think that this gives you what you need:

NSRect imageRect = [imageView.cell drawingRectForBounds: imageView.bounds];

which returns the offset of the origin of the image within the view, and it's size.

And for you end goal of remapping the mouse coordinates, something like this on your custom view class should work...

- (void)mouseUp:(NSEvent *)event
{
    NSPoint eventLocation = [event locationInWindow];    
    NSPoint location = [self convertPoint: eventLocation fromView: nil];

    NSRect drawingRect = [self.cell drawingRectForBounds:self.bounds];

    location.x -= drawingRect.origin.x;
    location.y -= drawingRect.origin.y;

    NSSize frameSize = drawingRect.size;
    float frameAspect = frameSize.width/frameSize.height;

    NSSize imageSize = self.image.size;
    float imageAspect = imageSize.width/imageSize.height;

    float scaleFactor = 1.0f;

    if(imageAspect > frameAspect) {

        ///in this case image.width == frame.width
        scaleFactor = imageSize.width / frameSize.width;

        float imageHeightinFrame = imageSize.height / scaleFactor;

        float imageOffsetInFrame = (frameSize.height - imageHeightinFrame)/2;

        location.y -= imageOffsetInFrame;

    } else {
        ///in this case image.height == frame.height
        scaleFactor = imageSize.height / frameSize.height;

        float imageWidthinFrame = imageSize.width / scaleFactor;

        float imageOffsetInFrame = (frameSize.width - imageWidthinFrame)/2;

        location.x -= imageOffsetInFrame;
    }

    location.x *= scaleFactor;
    location.y *= scaleFactor;

    //do something with you newly calculated mouse location    
}
like image 67
combinatorial Avatar answered Sep 21 '22 15:09

combinatorial