如何画线斯威夫特3
问题描述:
我想用户触摸2个点,然后线这两个点之间绘制。以下是我迄今为止:如何画线斯威夫特3
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)
}
}
上面的代码将每两个点选定的时间画一条线,当你喜欢,你可以自定义上述功能。
我希望这可以帮助您。
谢谢!我还有一个问题:我如何删除用户已绘制的线条 –
@CharlesB。欢迎你,你可以删除以前的''CAShapeLayer(用'removeFromSuperlayer')保存参考文献,它只是一个办法做到这一点 –
@Victor,我用你的FUNC addline和它的作品绘制细胞内一行。谢谢 –