您可以使用UIPanGestureRecognizer 获取手势事件并使用UIBezierPath 绘制CALayer。
UIPanGestureRecognizer 有一些手势状态,在这种情况下,我们需要处理三个状态来绘制线条。让我们将整个动作分成小块,以便更容易弄清楚要做什么。
在开始之前,你必须知道一件事。
// We can get current touch position via gesture recognizer.
let currentPanPoint = panRecognizer.location(in: self.view)
- 获取线路起点并在状态
UIGestureRecognizerState.began 中创建CALayer。
case .began:
panGestureStartPoint = currentPanPoint
self.view.layer.addSublayer(lineShape)
- 获取状态
UIGestureRecognizerState.changed的线端点并创建UIBezierPath,将UIBezierPath的CGPath分配给CALayer以绘制线。
case .changed:
let linePath = UIBezierPath()
linePath.move(to: panGestureStartPoint)
linePath.addLine(to: currentPanPoint)
lineShape.path = linePath.cgPath
- 从处于
UIGestureRecognizerState.end 状态的布局中删除行。
case .ended:
lineShape.path = nil
lineShape.removeFromSuperlayer()
结合上面的片段,这里是示例代码。
class ViewController: UIViewController {
@IBOutlet var dragFrom: UILabel!
private lazy var lineShape: CAShapeLayer = {
let lineShape = CAShapeLayer()
lineShape.strokeColor = UIColor.blue.cgColor
lineShape.lineWidth = 2.0
return lineShape
}()
private var panGestureStartPoint: CGPoint = .zero
private lazy var panRecognizer: UIPanGestureRecognizer = {
return UIPanGestureRecognizer(target: self, action: #selector(panGestureCalled(_:)))
}()
override func viewDidLoad() {
super.viewDidLoad()
self.dragFrom.addGestureRecognizer(panRecognizer)
}
// MARK: Selectors
func panGestureCalled(_: UIPanGestureRecognizer) {
let currentPanPoint = panRecognizer.location(in: self.view)
switch panRecognizer.state {
case .began:
panGestureStartPoint = currentPanPoint
self.view.layer.addSublayer(lineShape)
case .changed:
let linePath = UIBezierPath()
linePath.move(to: panGestureStartPoint)
linePath.addLine(to: currentPanPoint)
lineShape.path = linePath.cgPath
case .ended:
lineShape.path = nil
lineShape.removeFromSuperlayer()
default: break
}
}
}
它是这样工作的。
http://i.imgur.com/5JsFeoB.gifv
如果您想了解更多详细信息,请参阅 Apple 开发人员指南中的教程。 Learn how to draw shapes using Bezier Path