我正在开发一个 Mac 应用程序,我想知道触摸时手指在触控板上的位置。
这是否可能,如果可能,如何实现?
最佳答案
您的 View 需要设置为接受触摸 ([self setAcceptsTouchEvents:YES]
)。当你得到像 -touchesBeganWithEvent:
这样的触摸事件时,你可以通过查看它的 normalizedPosition
(范围是 [0.0, 1.0] x [0.0, 1.0]) 鉴于其 deviceSize
大点(每英寸有 72 bp)。触控板的左下角被视为零原点。
所以,例如:
- (id)initWithFrame:(NSRect)frameRect {
self = [super initWithFrame:frameRect];
if (!self) return nil;
/* You need to set this to receive any touch event messages. */
[self setAcceptsTouchEvents:YES];
/* You only need to set this if you actually want resting touches.
* If you don't, a touch will "end" when it starts resting and
* "begin" again if it starts moving again. */
[self setWantsRestingTouches:YES]
return self;
}
/* One of many touch event handling methods. */
- (void)touchesBeganWithEvent:(NSEvent *)ev {
NSSet *touches = [ev touchesMatchingPhase:NSTouchPhaseBegan inView:self];
for (NSTouch *touch in touches) {
/* Once you have a touch, getting the position is dead simple. */
NSPoint fraction = touch.normalizedPosition;
NSSize whole = touch.deviceSize;
NSPoint wholeInches = {whole.width / 72.0, whole.height / 72.0};
NSPoint pos = wholeInches;
pos.x *= fraction.x;
pos.y *= fraction.y;
NSLog(@"%s: Finger is touching %g inches right and %g inches up "
@"from lower left corner of trackpad.", __func__, pos.x, pos.y);
}
}
(将此代码视为示例,而不是久经考验的真实示例代码;我只是将其直接写在评论框中。)
关于objective-c - 在 Mac OS X 下知道手指在触控板上的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3573276/