我正在开发一个 Mac 应用程序,我想知道触摸时手指在触控板上的位置。
有没有可能,如果有,怎么做?
您的视图需要设置为接受触摸 ( [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);
}
}
(将此代码视为说明,而不是经过验证的真实示例代码;我只是将其直接写在评论框中。)
斯威夫特 3:
我已经为 NSTouch 编写了一个扩展,它返回相对于 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
}
}
这是我写的一篇关于我在 macOS 中的 GestureHUD 类的文章。还带有指向现成扩展的链接:http ://eon.codes/blog/2017/03/15/Gesture-HUD/
我不知道是否有 ObjC 接口,但您可能会发现 C HID 类设备接口很有趣。
在 Cocoa(Obj-C 级别)尝试以下操作 - 尽管请记住许多用户仍在使用鼠标控制。