I'm trying to draw lines with touches and then be able to move it. i didn't use UIContext method with draw(_ rect: CGRect) for drawing because i wasn't able to get size of stroke and some of it's properties, so i used CAShapeLayer for drawing with touches methods like this:
let shapeLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.lineWidth = 1
layer.strokeColor = UIColor.black.cgColor
layer.fillColor = UIColor.clear.cgColor
layer.lineCap = .round
layer.lineJoin = .round
layer.lineDashPattern = [10, 10]
layer.name = "ShapeLayer"
return layer
}()
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = 1
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineCap = .round
shapeLayer.lineJoin = .round
shapeLayer.lineDashPattern = [10, 10]
shapeLayer.name = "ShapeLayer"
self.canvas.layer.addSublayer(shapeLayer)
path = MyBezierPath()
if let location = touches.first?.location(in: self.canvas) { previousTouchPoint = location }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first?.location(in: self.canvas) else { return }
if let location = touches.first?.location(in: self.canvas) {
path.move(to: location)
path.addLine(to: previousTouchPoint)
previousTouchPoint = location
if canvas.layer.sublayers != nil && canvas.layer.sublayers?.last?.name == "ShapeLayer" {
guard let layer = canvas.layer.sublayers?.last as? CAShapeLayer else { return }
print("Here \(layer.path?.boundingBoxOfPath)")
layer.path = path.cgPath
}
}
}
i was trying to add all UIBezierpath to single CAShapeLayer so i can select particular path and move it. But in this method it creates new CAShapeLayer for every line so i tried defining global CAShapeLayer variable and appending UIBezierPath for all lines and add it to global CAShapeLayer variable but it's very slow and laggy. is there any way i can draw with only one CAShapeLayer then be able to change location of it's BezierPath?