如何在Swift 3中画一条线

Cha*_* B. 14 drawing swift

我希望用户触摸2个点,然后在这两个点之间绘制一条线.这是我到目前为止:

func drawline(){
    let context = UIGraphicsGetCurrentContext()
    context!.beginPath()
    context?.move(to: pointA)
    context?.addLine(to: pointB)
    context!.strokePath()
}
Run Code Online (Sandbox Code Playgroud)

pointA是用户触及的第一点,pointB也是第二点.我收到错误:

thread 1:EXC_BREAKPOINT
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助.

Vic*_*ler 28

要在两点之间画一条线,你需要的第一件事是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)
   }
}
Run Code Online (Sandbox Code Playgroud)

每次选择两个点时,上面的代码将绘制一条线,您可以根据需要自定义上述功能.

我希望这对你有帮助.