swift - 如何在 Swift 3 中画一条线

标签 swift drawing

我希望用户触摸 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/

相关文章:

android - 如何在 Android 中绘制支持触摸的矩形

c - 找到缩放元素的正确位置(添加图表)

ios - 目标选择器不适用于 Swift3

ios - 重用 API 管理器类和存储数据以使其可重用的最佳方法是什么

ios - 是否可以重用 cellForItemAtIndexPath :?

.net - 使用起点 X/Y 和起点 + 扫掠角在 ArcSegment 中获取终点

swift - 检测绝对垂直轴上的加速度

ios - "Reached the max number of texture atlases, can not allocate more"使用谷歌地图

ios - 我如何绘制两条线之间有一定角度的线,以后可以通过拖动任何线来改变角度

java - 绘制随机圆圈,将其坐标存储在数组中