【问题标题】:Detecting stroked uibezierpath contains point检测描边的uibezierpath包含点
【发布时间】:2018-02-13 03:36:33
【问题描述】:

我正在我的视图中绘制一条描边路径。我正在尝试查看描边路径是否包含特定点。但是它的 contains 方法不会检测该点是否在描边路径中。

func checkCollision(currentPoint:CGPoint) -> CustomShape?{
    for shape in customShapes {
        //Check if current shapes uibezierpath contains a point
        if (shape.path.contains(currentPoint)) {
            return shape
        }
    }
    return nil
}

【问题讨论】:

  • 我们可以看看一些代码吗?
  • 您的意思是... a) 该点位于封闭路径内,b) 该点在过去某个时间以编程方式添加到路径中...或 c) 该点理论上完全正确与路径相交?
  • @BooberBunz 点与路径相交。

标签: ios swift mobile uibezierpath


【解决方案1】:

斯威夫特 5.x

您可以使用此扩展来快速回答:

extension UIBezierPath {
    func isInsideBorder(_ pos:CGPoint, tolleranceWidth:CGFloat = 2.0)->Bool{
        let pathRef = cgPath.copy(strokingWithWidth: tolleranceWidth, lineCap: CGLineCap.butt, lineJoin: CGLineJoin.round, miterLimit: 0)
        let pathRefMutable = pathRef.mutableCopy()
        if let p = pathRefMutable {
            p.closeSubpath()
            return p.contains(pos)
        }
        return false
    }
}

用法:

var currentPoint:CGPoint= CGPoint.zero
if yourBeizerPath.isInsideBorder(currentPoint, tolleranceWidth:3.0) {
   /// Let's go, it's inside..
}

【讨论】:

    【解决方案2】:

    覆盖自定义UIViewhitTest(_:with:) 实例方法。此方法返回当前视图最远的后代并包含point 的视图对象。如果该点完全位于接收者的视图层次结构之外,则返回 nil

    https://developer.apple.com/documentation/uikit/uiview/1622469-hittest

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        guard path.contains(point) else {
            return nil
        }
        return self
    }
    

    【讨论】:

      【解决方案3】:

      检查点是否在描边路径内的一种方法是复制路径并使用 cgPath 的复制方法添加描边。

      let strokedPath = yourPath.cgPath.copy(
         strokingWithWidth: 10, 
         lineCap: CGLineCap.butt, 
         lineJoin: CGLineJoin.miter, 
         miterLimit: 0
      ) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-25
        • 1970-01-01
        • 2018-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多