我希望用户触摸 2 个点,然后在这两点之间画一条线。这是我目前所拥有的:
func drawline(){
let context = UIGraphicsGetCurrentContext()
context!.beginPath()
context?.move(to: pointA)
context?.addLine(to: pointB)
context!.strokePath()
}
pointA
是用户触摸的第一个点,pointB
是第二个点。我收到错误:
thread 1:EXC_BREAKPOINT
预先感谢您的帮助。
最佳答案
要在两点之间画一条线,您需要做的第一件事是从当前 UIView
获取 CGPoints
,有几种方法可以实现这一点。为了示例的缘故,我将使用 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)
}
}
上面的代码是每选中两个点就画一条线,你可以根据需要自定义上面的函数。
希望对你有帮助
关于swift - 如何在 Swift 3 中画一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40556112/