знать положение пальца в трекпаде под Mac OS X - PullRequest
11 голосов
/ 26 августа 2010

Я занимаюсь разработкой приложения для Mac и хотел бы знать положение пальца в трекпаде при касании.

Возможно ли это, и если да, то как?

Ответы [ 4 ]

12 голосов
/ 25 сентября 2010

Ваш вид должен быть настроен на прием касаний ([self setAcceptsTouchEvents:YES]). Когда вы получаете событие касания, например -touchesBeganWithEvent:, вы можете определить, где находится палец, взглянув на его normalizedPosition (диапазон [0,0, 1,0] x [0,0, 1,0]) в свете его deviceSize в большом очки (есть 72 б.п. на дюйм). Нижний левый угол трекпада рассматривается как нулевое начало.

Так, например:

- (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);
   }
}

(Рассматривайте этот код как иллюстрацию, а не как проверенный и верный, изношенный в бою пример кода; я просто написал его прямо в поле для комментариев.)

3 голосов
/ 23 января 2017

Swift 3:

Я написал расширение для NSTouch, которое возвращает трекпад touch pos относительно NSView:

extension NSTouch {
    /**
     * Returns the relative position of the touch to the view
     * NOTE: the normalizedTouch is the relative location on the trackpad. values range from 0-1. And are y-flipped
     * TODO: debug if the touch area is working with a rect with a green stroke
     */
    func pos(_ view:NSView) -> CGPoint{
        let w = view.frame.size.width
        let h = view.frame.size.height
        let touchPos:CGPoint = CGPoint(self.normalizedPosition.x,1 + (self.normalizedPosition.y * -1))/*flip the touch coordinates*/
        let deviceSize:CGSize = self.deviceSize
        let deviceRatio:CGFloat = deviceSize.width/deviceSize.height/*find the ratio of the device*/
        let viewRatio:CGFloat = w/h
        var touchArea:CGSize = CGSize(w,h)
        /*Uniform-shrink the device to the view frame*/
        if(deviceRatio > viewRatio){/*device is wider than view*/
            touchArea.height = h/viewRatio
            touchArea.width = w
        }else if(deviceRatio < viewRatio){/*view is wider than device*/
            touchArea.height = h
            touchArea.width = w/deviceRatio
        }/*else ratios are the same*/
        let touchAreaPos:CGPoint = CGPoint((w - touchArea.width)/2,(h - touchArea.height)/2)/*we center the touchArea to the View*/
        return CGPoint(touchPos.x * touchArea.width,touchPos.y * touchArea.height) + touchAreaPos
    }
}

статья, которую я написал о своем классе GestureHUD в macOS.Со ссылкой на готовое расширение: http://eon.codes/blog/2017/03/15/Gesture-HUD/

Пример:

example

1 голос
/ 26 августа 2010

Не знаю, есть ли интерфейс ObjC, но вам может показаться интересным интерфейс устройства класса C HID .

0 голосов
/ 26 августа 2010

На Какао (уровень Obj-C) попробуйте следующее - хотя помните, что многие пользователи все еще используют управление мышью.

http://developer.apple.com/mac/library/documentation/cocoa/conceptual/EventOverview/HandlingTouchEvents/HandlingTouchEvents.html

...