【问题标题】:How to detect cgPath in cgRect如何检测 cgRect 中的 cgPath
【发布时间】:2019-10-29 23:00:26
【问题描述】:

我只能检测到包含在 c1 中的起点(touchBegan)和包含在 c2 中的终点(touchEnded),但我无法在 c3 中检测到它们之间的路径,我该怎么办?

Application image

override func layoutSubviews() {
    self.clipsToBounds = true
    self.isMultipleTouchEnabled = false
    self.contentMode = .scaleToFill
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    swiped = false
    lastPoint = touch?.location(in: self)
    firstPoint = lastPoint
}


override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
    swiped = true
    let currentPoint = touch?.location(in: self) 
    lastPoint = currentPoint
    linePoint = lastPoint
    drawShapeLayer(from: lastPoint, to: currentPoint!)
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if !swiped {
        drawShapeLayer(from: lastPoint, to: lastPoint!)
    }

    if  c1.contains(firstPoint) && c3.contains(linePoint) && c2.contains(lastPoint){
        AlertView.instance.showAlert(title: "Hooray!", message: "You made it!", alertType : .success)
    }

    else {
         AlertView.instance.showAlert(title: "Oops!", message: "You've almost got it.", alertType : .failure)
    }
}
}

【问题讨论】:

  • iirc 当您在不调用 super 的情况下覆盖甚至覆盖其中一个触摸事件方法时,即使覆盖什么也不做,您也应该覆盖它们。 touchesCancelled(_:with:) 在这里没有被覆盖。
  • 另外我认为您在touchesMoved 中存在逻辑错误。您正在分配 lastPoint = currentPoint,然后是 linePoint = lastPoint,因此所有三个变量都具有相同的值 (currentPoint)。您尝试从 lastPoint 绘制到 currentPoint,但这些现在是同一个点,因此不会画线。当您测试所有这些点时,它还会对 touchesEnded 产生连锁反应。

标签: swift xcode uibezierpath cgrect cgpath


【解决方案1】:

根据我上面的 cmets,我认为 touchesMoved 中存在逻辑错误,如果您尝试绘制三点线,则需要重新排序代码,然后检查每个点是否在特定的查看区域。

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
      swiped = true
      currentPoint = touch.location(in: self)
      drawShapeLayer(from: lastPoint, to: currentPoint)
      lastPoint = currentPoint
      linePoint = currentPoint
   }
}

(还可以安全地展开 touch 以删除可选项并避免在 touches.first 为 nil 的不太可能的情况下崩溃)

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多