gpt4 book ai didi

cocoa - 当父级不是窗口时,有没有办法获取相对于最里面的 NSView 的坐标?

转载 作者:行者123 更新时间:2023-12-03 16:02:43 25 4
gpt4 key购买 nike

我对 NSView 有疑问:

想象一个自定义 View ,其中 mouseDown、mouseDrag 和 mouseUp 方法被重写,以便用户可以在屏幕上拖动点 (NSRect)。要拖动它,我需要相对于当前 View 的鼠标坐标。当 View 的父级是窗口时这不是问题,但是当 View 位于另一个 View 内时如何获取它们?

@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];
}
}

最佳答案

您不需要手动转换为本地坐标系。您可以通过向 View 发送 convertPoint:fromView: 消息将点转换为本地坐标系。将 nil 作为参数发送给 fromView 将从 View 的父窗口(无论在哪里)转换点。您还可以发送任何其他 View 来获取从该空间转换的坐标:

// 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];

关于cocoa - 当父级不是窗口时,有没有办法获取相对于最里面的 NSView 的坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/434424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com