我希望用户触摸2点,然后在这两点之间画一条线。这是我到目前为止的内容:
func drawline(){
let context = UIGraphicsGetCurrentContext()
context!.beginPath()
context?.move(to: pointA)
context?.addLine(to: pointB)
context!.strokePath()
}
pointA
是用户触摸的第一点,而pointB
是用户触摸的第二点。我得到错误:thread 1:EXC_BREAKPOINT
在此先感谢您的帮助。
最佳答案
要在两点之间画一条线,首先需要从当前CGPoints
获取UIView
,有几种方法可以实现这一点。为了示例,我将使用UITapGestureRecognizer
来检测何时单击。
下一步是一旦保存了两个点,就在两个点之间画线,为此,您可以再次使用图形上下文,也可以使用CAShapeLayer
。
因此,翻译上面解释的内容,我们得到以下代码:
class ViewController: UIViewController {
var tapGestureRecognizer: UITapGestureRecognizer!
var firstPoint: CGPoint?
var secondPoint: CGPoint?
override func viewDidLoad() {
super.viewDidLoad()
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.showMoreActions(touch:)))
tapGestureRecognizer.numberOfTapsRequired = 1
view.addGestureRecognizer(tapGestureRecognizer)
}
func showMoreActions(touch: UITapGestureRecognizer) {
let touchPoint = touch.location(in: self.view)
guard let _ = firstPoint else {
firstPoint = touchPoint
return
}
guard let _ = secondPoint else {
secondPoint = touchPoint
addLine(fromPoint: firstPoint!, toPoint: secondPoint!)
firstPoint = nil
secondPoint = nil
return
}
}
func addLine(fromPoint start: CGPoint, toPoint end:CGPoint) {
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.move(to: start)
linePath.addLine(to: end)
line.path = linePath.cgPath
line.strokeColor = UIColor.red.cgColor
line.lineWidth = 1
line.lineJoin = kCALineJoinRound
self.view.layer.addSublayer(line)
}
}
上面的代码将在每次选择两个点时画一条线,您可以根据需要自定义上面的函数。
希望对您有帮助。