code_junkie

Is there a way to get coordinates relative to the innermost NSView when the parent is not the window?

Nov 13th, 2011
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. @implementation MyView
  2.  
  3. - (id)initWithFrame:(NSRect)frame {
  4. self = [super initWithFrame:frame];
  5. if (self) {
  6. pointXPosition = 200.0f;
  7. pointYPosition = 200.0f;
  8.  
  9. locked = NO;
  10. }
  11. return self;
  12. }
  13.  
  14. - (void) drawRect:(NSRect)rect {
  15.  
  16. NSRect point = NSMakeRect(pointXPosition, pointYPosition, 6.0f, 6.0f);
  17. [[NSColor redColor] set];
  18. NSRectFill(point);
  19.  
  20. }
  21.  
  22. - (void)mouseDown:(NSEvent *)theEvent {
  23. NSPoint mousePos = [theEvent locationInWindow];
  24. NSRect frame = [super frame];
  25. CGFloat deltaX = mousePos.x - frame.origin.x - pointXPosition;
  26. CGFloat deltaY = mousePos.y - frame.origin.y - pointYPosition;
  27. if(sqrtf(deltaX * deltaX + deltaY * deltaY) < 100.0f)
  28. locked = YES;
  29. }
  30.  
  31. - (void)mouseUp:(NSEvent *)theEvent {
  32. locked = NO;
  33. }
  34.  
  35. - (void)mouseDragged:(NSEvent *)theEvent {
  36.  
  37. if(locked) {
  38. NSPoint mousePos = [theEvent locationInWindow];
  39.  
  40. NSRect frame = [super frame];
  41.  
  42. CGFloat oldXPos = pointXPosition;
  43. CGFloat oldYPos = pointYPosition;
  44.  
  45. pointXPosition = mousePos.x - frame.origin.x;
  46. pointYPosition = mousePos.y - frame.origin.y;
  47.  
  48. CGFloat rectToDisplayXMin = MIN(oldXPos, pointXPosition);
  49. CGFloat rectToDisplayYMin = MIN(oldYPos, pointYPosition);
  50.  
  51. CGFloat rectWidthToDisplay = MAX(oldXPos, pointXPosition) - rectToDisplayXMin;
  52. CGFloat rectHeigthToDisplay = MAX(oldYPos, pointYPosition) - rectToDisplayYMin;
  53.  
  54. NSRect dirtyRect = NSMakeRect(rectToDisplayXMin,
  55. rectToDisplayYMin,
  56. rectWidthToDisplay + 6.0f,
  57. rectHeigthToDisplay + 6.0f);
  58.  
  59. [self setNeedsDisplayInRect:dirtyRect];
  60. }
  61. }
  62.  
  63. // convert from the window's coordinate system to the local coordinate system
  64. NSPoint clickPoint = [self convertPoint:[theEvent locationInWindow] fromView:nil];
  65.  
  66. // convert from some other view's cooridinate system
  67. NSPoint otherPoint = [self convertPoint:somePoint fromView:someSuperview];
Add Comment
Please, Sign In to add comment