2009-01-12 31 views
12

我對NSView有疑問:當父窗口不是窗口時,有沒有辦法獲得相對於最內層NSView的座標?

想象一下自定義視圖,其中mouseDown,mouseDrag和mouseUp方法被重寫,因此用戶可以在屏幕上拖動一個點(NSRect)。要拖動它,我需要相對於當前視圖的鼠標座標。當視圖的父窗口是窗口時,這不是問題,但當視圖位於另一個視圖內時,如何獲取它們?

@implementation MyView 

- (id)initWithFrame:(NSRect)frame { 
    self = [super initWithFrame:frame]; 
    if (self) { 
     pointXPosition = 200.0f; 
     pointYPosition = 200.0f; 

     locked = NO; 
    } 
    return self; 
} 

- (void) drawRect:(NSRect)rect { 

    NSRect point = NSMakeRect(pointXPosition, pointYPosition, 6.0f, 6.0f); 
    [[NSColor redColor] set]; 
    NSRectFill(point); 

} 

- (void)mouseDown:(NSEvent *)theEvent { 
    NSPoint mousePos = [theEvent locationInWindow]; 
    NSRect frame = [super frame]; 
    CGFloat deltaX = mousePos.x - frame.origin.x - pointXPosition; 
    CGFloat deltaY = mousePos.y - frame.origin.y - pointYPosition; 
    if(sqrtf(deltaX * deltaX + deltaY * deltaY) < 100.0f) 
     locked = YES; 
} 

- (void)mouseUp:(NSEvent *)theEvent { 
    locked = NO; 
} 

- (void)mouseDragged:(NSEvent *)theEvent { 

    if(locked) { 
     NSPoint mousePos = [theEvent locationInWindow]; 

     NSRect frame = [super frame]; 

     CGFloat oldXPos = pointXPosition; 
     CGFloat oldYPos = pointYPosition; 

     pointXPosition = mousePos.x - frame.origin.x; 
     pointYPosition = mousePos.y - frame.origin.y; 

     CGFloat rectToDisplayXMin = MIN(oldXPos, pointXPosition); 
     CGFloat rectToDisplayYMin = MIN(oldYPos, pointYPosition); 

     CGFloat rectWidthToDisplay = MAX(oldXPos, pointXPosition) - rectToDisplayXMin; 
     CGFloat rectHeigthToDisplay = MAX(oldYPos, pointYPosition) - rectToDisplayYMin; 

     NSRect dirtyRect = NSMakeRect(rectToDisplayXMin, 
             rectToDisplayYMin, 
             rectWidthToDisplay + 6.0f, 
             rectHeigthToDisplay + 6.0f); 

     [self setNeedsDisplayInRect:dirtyRect]; 
    } 
} 

回答

23

您不需要手動轉換到本地座標系。您可以通過將convertPoint:fromView:消息發送到您的視圖來將該點轉換爲本地座標系。發送nil作爲fromView的參數將從視圖的父窗口(無論哪裏)轉換該點。您還可以發送任何其他視圖以獲得從該空間轉換的座標:

// convert from the window's coordinate system to the local coordinate system 
NSPoint clickPoint = [self convertPoint:[theEvent locationInWindow] fromView:nil]; 

// convert from some other view's cooridinate system 
NSPoint otherPoint = [self convertPoint:somePoint fromView:someSuperview]; 
相關問題