我正在开发一个Mac应用程序,我想知道触摸时手指在触控板上的位置。
是否有可能,如果可以,怎么样?
答案 0 :(得分:12)
您的观点需要设置为接受触摸([self setAcceptsTouchEvents:YES]
)。当你得到像-touchesBeganWithEvent:
这样的触摸事件时,你可以根据normalizedPosition
(范围是[0.0,1.0] x [0.0,1.0])找出手指所在的位置{ {1}}大点(每英寸72 bp)。触控板的左下角被视为零原点。
所以,例如:
deviceSize
(将此代码视为插图,而不是经过验证的真实的战斗样本代码;我只是将其直接写入评论框。)
答案 1 :(得分:3)
斯威夫特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/
答案 2 :(得分:1)
我不知道是否有ObjC接口,但您可能会发现C HID Class Device Interface很有趣。
答案 3 :(得分:0)
在Cocoa(Obj-C级别)尝试以下操作 - 尽管记住许多用户仍在使用鼠标控件。