Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an NSPoint from window coordinates to view coordinates

My application has a custom view that displays a timeline of events. This view is wrapped in an NSScrollView to support horizontal scrolling of the timeline. Using notifications, I've implemented a mechanism that should show another custom view which displays detail information about an event when the user clicks that event in the timeline. Below is the code that handles the event when it is received by the timeline:

NSEvent *anEvent = [aNotification object];
NSPoint aLocationInSelf = [self convertPoint: [anEvent locationInWindow] toView: self];

// Create callout view and display
NSRect aRect = NSMakeRect(aLocationInSelf.x, aLocationInSelf.y, 300, 200);
TimelineCallout *aCallout = [[TimelineCallout alloc] initWithFrame: aRect];
[self addSubview: aCallout];

In the above code I do a conversion of the point of the mouse click as registered by the event from window coordinates to view (timeline) coordinates.

However, when I step through this with the debugger no conversion is taking place and locationInSelf shows the same coordinates as the point I get from [anEvent locationInWindow]. As a result the callout is drawn at the wrong place or not visible at all.

I must be doing something wrong but I can't figure out what...

like image 467
Roger Avatar asked Nov 06 '11 17:11

Roger


1 Answers

In order to convert from window coordinates to view coordinates, you have to use:

NSPoint aLocationInSelf = [self convertPoint: [anEvent locationInWindow] fromView: nil];

This will convert from window base coordinates to the receiver coordinates as the event is not originated from a particular view.

For more information, refer to the documentation.

More detailed explanation:

The conversion methods are a bit tricky to understand. There mainly two general cases (the other ones are variants):

  1. Convert a point from one view to another view when they are located in the same window
  2. Convert a point expressed in window coordinate into view coordinates

For the 1st case, you have two views (view1 and view2) located in the same window. If you want to convert a point from view2 into the view1's coordinate system the code will be:

NSPoint pointInView1 = [view1 convertPoint:pointInView2 fromView:view2];

For the 2nd case, you have a point expressed in window coordinates (from the event). As the point is expressed in window coordinates, you don't specify a "from" view and the code will be:

NSPoint pointInView1 = [view1 convertPoint:pointInWindow fromView:nil];

This is the fallback behavior of the method.

like image 131
Laurent Etiemble Avatar answered Sep 24 '22 04:09

Laurent Etiemble