问题描述
我试图用UIbezierPath绘制多个,但是每当我尝试绘制第二个时,第一个消失。试图创建多个BezierPath并将它们放入数组,但是当它运行到case:ended
test[2687:238999] [UnkNown process name] CGPathCloseSubpath: no current point.
这是我的代码
private lazy var lineshape: CAShapeLayer = {
let lineshape = CAShapeLayer()
lineshape.strokeColor = UIColor.blue.cgColor
lineshape.linewidth = 2.0
return lineshape
}()
var bezierPathArr:NSMutableArray = []
private var panGestureStartPoint: CGPoint = .zero
private lazy var panRecognizer: UIPanGestureRecognizer = {
return UIPanGestureRecognizer(target: self,action: #selector(panGestureCalled(_:)))
}()
@objc func panGestureCalled(_: UIPanGestureRecognizer) {
let linePath = UIBezierPath()
let currentPanPoint = panRecognizer.location(in: self.view)
switch panRecognizer.state {
case .began:
panGestureStartPoint = currentPanPoint
self.view.layer.addSublayer(lineshape)
bezierPathArr.add(linePath)
case .changed:
linePath.move(to: panGestureStartPoint)
linePath.addLine(to: currentPanPoint)
lineshape.path = linePath.cgPath
case .ended:
let finalPath:UIBezierPath = bezierPathArr.lastObject as! UIBezierPath
finalPath.close()
default: break
}
}
解决方法
由于lazy
的{{1}}创建,因此,每当向视图中添加图层时,都使用相同的对象引用。连同在该引用上设置路径一起,您将获得所遇到的行为。
为了达到预期的行为,您需要为每个完成的手势创建并存储一个新的CAShapeLayer
。这是一个工作示例:
CAShapeLayer