如何在Swift 3中绘制一条直线

15

我希望用户能够触摸屏幕上的两个点,然后在这两个点之间绘制一条直线。以下是我的实现代码:

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

pointA是用户触摸的第一个点,pointB是第二个点。我遇到了错误:

thread 1:EXC_BREAKPOINT

感谢您提前的帮助。

2个回答

30

为了在两个点之间画一条线,首先需要从当前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)
   }
}

上述代码将在选择两个点时绘制一条线,您可以根据需要自定义上述函数。

我希望这对您有所帮助。


谢谢!我有另一个问题:用户如何删除他们画的线条? - Charles B.
1
@CharlesB。不用谢,您可以使用removeFromSuperlayer删除之前的CAShapeLayer(并保存引用),这只是一种方法。 - Victor Sigler
1
@Victor,我使用了你的addline函数,在单元格内绘制一条线,它很有效。谢谢。 - Xin Lok

1

在Swift 4.1中画线

class MyViewController: UIViewController {

    @IBOutlet weak var imgViewDraw: UIImageView!

    var lastPoint = CGPoint.zero
    var red: CGFloat = 0.0
    var green: CGFloat = 0.0
    var blue: CGFloat = 0.0
    var brushWidth: CGFloat = 10.0
    var opacity: CGFloat = 1.0
    var isSwiping:Bool!


    override func viewDidLoad() {
        super.viewDidLoad()


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    //MARK: Touch events
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        isSwiping    = false
        if let touch = touches.first{
            lastPoint = touch.location(in: imgViewDraw)
        }
    }
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        isSwiping = true;
        if let touch = touches.first{
            let currentPoint = touch.location(in: imgViewDraw)
            UIGraphicsBeginImageContext(self.imgViewDraw.frame.size)
            self.imgViewDraw.image?.draw(in: CGRect(x:0, y:0,width:self.imgViewDraw.frame.size.width, height:self.imgViewDraw.frame.size.height))

            UIGraphicsGetCurrentContext()?.move(to: CGPoint(x: lastPoint.x, y: lastPoint.y))
            UIGraphicsGetCurrentContext()?.addLine(to: CGPoint(x: currentPoint.x, y: currentPoint.y))

            UIGraphicsGetCurrentContext()?.setLineCap(CGLineCap.round)
            UIGraphicsGetCurrentContext()?.setLineWidth(self.brushWidth)
            UIGraphicsGetCurrentContext()?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
            UIGraphicsGetCurrentContext()?.strokePath()


            self.imgViewDraw.image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            lastPoint = currentPoint
        }
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if(!isSwiping) {
            // This is a single touch, draw a point
            UIGraphicsBeginImageContext(self.imgViewDraw.frame.size)
            self.imgViewDraw.image?.draw(in: CGRect(x:0, y:0,width:self.imgViewDraw.frame.size.width, height:self.imgViewDraw.frame.size.height))
            UIGraphicsGetCurrentContext()?.setLineCap(CGLineCap.round)
            UIGraphicsGetCurrentContext()?.setLineWidth(self.brushWidth)

            UIGraphicsGetCurrentContext()?.move(to: CGPoint(x: lastPoint.x, y: lastPoint.y))
            UIGraphicsGetCurrentContext()?.addLine(to: CGPoint(x: lastPoint.x, y: lastPoint.y))
            UIGraphicsGetCurrentContext()?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
            UIGraphicsGetCurrentContext()?.strokePath()
            self.imgViewDraw.image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
        }
    }


}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接