Converting an NSPoint from window coordinates to view coordinates

主宰稳场 提交于 2019-11-29 11:53:24

问题


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...


回答1:


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.



来源:https://stackoverflow.com/questions/8028775/converting-an-nspoint-from-window-coordinates-to-view-coordinates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!