无法在CAShapeLayer lineWidth上检测到抽头事件吗?

时间:2019-07-18 12:32:14

标签: swift uibezierpath cashapelayer

我已经使用Bezier路径创建了一个圆,还创建了点击事件来检查图层是否被点击,在我增加CAShapeLayer的lineWidth大小之前,它工作正常。通过点击lineWidth,有时会检测到它,有时却无法检测到它。

我在stackoverflow上搜索了我遇到的问题,但无法解决。问题仍然相同,我无法在我的图层(lineWidth区域)上检测到某些轻拍。

我只想检测CAShapeLayer的lineWidth上的抽头,我一直在搜索,但是找不到合适的解决方案。大多数答案都是过时的语言。如果有人能提供示例解决我的问题,我将不胜感激。雨燕4。

https://i.imgur.com/194Aljn.png


let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapDetected(tapRecognizer:)))
    self.addGestureRecognizer(tapRecognizer)

@objc public func tapDetected(tapRecognizer:UITapGestureRecognizer) {
    let tapLocation:CGPoint = tapRecognizer.location(in: self)
    self.hitTest(tapLocation: CGPoint(x: tapLocation.x, y: tapLocation.y))
}


private func hitTest(tapLocation:CGPoint) {
    if layer.path?.contains(tapLocation) == true {
        print("Do something")
    } else {
        print("Nothing Found")
    }
}




1 个答案:

答案 0 :(得分:0)

问题在于,线条描边实际上不是路径的一部分-只是它显示的一部分。您可以使用某些CGPath方法将路径转换为包含笔画的较大路径:

let pathWithLineStroke = UIBezierPath.init(cgPath: path.cgPath.copy(strokingWithWidth: 2.0, lineCap: CGLineCap.butt, lineJoin: .bevel, miterLimit: 1.0));

当然可以用实际值替换widthlineCaplineJoinmiterLimit

我建议您在代码中更早地进行此操作,然后仅绘制已内置笔触的路径,而不是在CALayer上设置这些属性。

希望有帮助。祝你好运。