objective-c - 在 Mac OS X 下知道手指在触控板上的位置

标签 objective-c cocoa macos trackpad

我正在开发一个 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/

相关文章:

xcode - 未知类型名称 Xcode 恶作剧

python - 如何在 Mac OS X 上安装 Python 开发头文件?

ruby-on-rails - 为什么我不能使用 RVM 在 Lion 上安装 Rails?

objective-c - animateWithDuration 如何知道要为什么设置动画?

objective-c - 从计算机时钟引用的时间码

cocoa - iTunes 中具有额外排序功能的新的较高表格标题行是如何实现的?

reactjs - 我是否错误地安装了 create-react-app?

ios - 属性和 ivars 的问题

ios - 将 NSRangePointer 从 Objective-C 翻译成 Swift

ios - 如何绘制围绕右上角和右下角的对象流动的文本?