如何在Swift 3中画一条线 [英] How to draw a line in Swift 3
问题描述
我希望用户触摸2点,然后在这两点之间画一条线。这是我到目前为止的内容:
I would like the user to touch 2 points and then a line is drawn between those two points. Here is what I have so far:
func drawline(){
let context = UIGraphicsGetCurrentContext()
context!.beginPath()
context?.move(to: pointA)
context?.addLine(to: pointB)
context!.strokePath()
}
pointA
是用户触摸的第一点,并且 pointB
是第二点。我收到错误消息:
pointA
is the first point the user touched and pointB
is the second point. I get the error:
thread 1:EXC_BREAKPOINT
在此先感谢您的帮助。
推荐答案
在两条线之间画一条线要点,首先需要从当前的 UIView
获取 CGPoints
,有几种方法可以实现。为了示例,我将使用 UITapGestureRecognizer
来检测您何时点击。
To draw a line between two points the first thing you need is get the CGPoints
from the current UIView
, there are several ways of achieve this. I going to use an UITapGestureRecognizer
for the sake of the sample to detect when you make a tap.
步骤是,一旦保存了两个点,就在两个点之间绘制了一条线,然后可以再次使用图形上下文,或者使用 CAShapeLayer
。
The another step is once you have the two points saved draw the line between the two points, and for this again you can use the graphics context as you try before or use CAShapeLayer
.
因此,通过翻译上面的解释,我们得到以下代码:
So translating the explained above we get the following code:
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)
}
}
上面的代码将在每次选择两个点时画一条线,您可以根据需要自定义上面的函数。
The above code is going to draw a line every time two points are selected and you can customize the above function as you like.
希望对您有所帮助。
这篇关于如何在Swift 3中画一条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!