我画了一个10点宽的路径,但是当我试图检测其中的touch 时,UIBezierPath包含:method只检测发生在1像素行而不是10像素行的touch .

    let path = UIBezierPath()
    path.move(to: start)
    path.addLine(to: end)
    path.usesEvenOddFillRule = true
    path.lineWidth = 10
    path.lineCapStyle = .round
    path.stroke()
    path.close()

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = lineColor.cgColor
    shapeLayer.lineWidth = path.lineWidth

下面是一个检测touch 的方法:

@objc func didTapOnView(_ recognizer: UIGestureRecognizer) {
    let tapLocation:CGPoint = recognizer.location(in: self)
    self.hitTest(tapLocation: CGPoint(x: tapLocation.x.rounded(), y: tapLocation.y.rounded()))
}

private func hitTest(tapLocation: CGPoint){

    let path: UIBezierPath = path0

    print("Touch location is: \(tapLocation)")

    if path.contains(tapLocation){
       print("inside")
    } else{
        print("outside")
    }
}

我只得到发生在精确的1像素线,而不是在10像素线的touch .如果我不做舍入,根本不会检测到任何touch .

推荐答案

你的路似乎只是一条线.对于一条线,contains只对该线上的点返回true.它不考虑笔划宽度.当然,几乎不可能在一条线上点击exactly,这就是为什么你根本不会检测到任何touch ,除非你把touch 位置圆化.

你可以用copy(strokingWithWidth:lineCap:lineJoin:miterLimit:transform:)得到一个CGPath,代表UIBezierPathstroked area.然后,您可以使用contains来判断一个点是否在该区域内.

let path: UIBezierPath = path0.cgPath.copy(
    strokingWithWidth: 10,
    lineCap: .butt,
    lineJoin: .miter,
    miterLimit: 10
)

if path.contains(somePoint, using: .evenOdd) { ... }

Ios相关问答推荐

无法在fastlane和github操作中从react-native 应用程序构建ios

我想在expo 中使用useSafeAreaInsets来获取paddingbottom,但我得到了一个错误

Nomb iOS 17.4.0中崩溃

一堆UIGraphics方法在iOS 17中被弃用,没有明确的替代方法?

由于已存在同名项目,因此无法将Mapbox.xcframework-ios.sign复制到Signature中

使用标头UICollectionViewFlowLayout时的简单SwiftUI视图错误

flutter中实现自定义底部导航栏

确保方法调配的安全有效实施

RealityKit – ARView 光线投射返回 0 个结果

SwiftUI 切换语句

将视图(例如 Text())不透明度设置为 0 或将背景设置为 Color.clear 会导致它不被绘制

使用导航控制器在prepareForSegue中设置数据

从 NSData 或 UIImage 中查找图像类型

在 iPhone 应用程序中使用 SSL - 出口合规性

使用 Xcode 4 的 iPhone 临时构建

自动布局:是什么创建了名为 UIView-Encapsulated-Layout-Width & Height 的约束?

iOS7 UITextView contentsize.height 替代

如何为 UILabel 的背景 colored颜色 设置动画?

更改标签栏项目图像和文本 colored颜色 iOS

iOS 7 应用程序图标、启动图像和命名约定,同时保留 iOS 6 图标