Search code examples
arraysswiftuibezierpathcashapelayerbezier

How to create a multiple path from several BezierPath


I'm working with swift 2.2 and I'm dealing with such problem: I have an array of UIBezier objects and I need to create a stroke for them as one path.

I used to have a special function for that, but the pros of that approach, that it created several layers. That goes along with my requirements, as I need one layer

 func createStroke(line: UIBezierPath) {

        self.currentPath = CAShapeLayer()
        currentPath.path = line.CGPath
        currentPath.strokeColor = UIColor.blackColor().CGColor
        currentPath.fillColor = UIColor.clearColor().CGColor
        currentPath.lineWidth = 1
        self.view.layer.addSublayer(currentPath)

    }

What is the best way to create a multiple path from an array of my Bezier lines? The first idea is to create a for-loop cycle, but I consider it is not a clean way.


Solution

  • You can do something like this (this is playground code):

    let myView = UIView(frame:CGRect(x: 100, y: 100, width: 250, height: 250))
    myView.backgroundColor = UIColor.white
    let myLayer = CAShapeLayer()
    
    func createPath(i: Int) -> UIBezierPath {
        let path = UIBezierPath()
        path.move(to: CGPoint(x: 2*i, y: 9*i - 4))
        path.addLine(to: CGPoint(x: 10 + 5*i, y: 20 + 4*i))
    
        return path
    }
    
    func createStroke(line: UIBezierPath) {
        myLayer.path = line.cgPath
        myLayer.strokeColor = UIColor.black.cgColor
        myLayer.fillColor = UIColor.black.cgColor
        myLayer.lineWidth = 1
    }
    
    let paths = [createPath(i: 0), createPath(i: 15), createPath(i: 8), createPath(i: 10)]
    let myPath = UIBezierPath()
    for path in paths {
        myPath.append(path) // THIS IS THE IMPORTANT PART
    }
    createStroke(line: myPath)
    myView.layer.addSublayer(myLayer)
    
    myView
    

    here is what it looks like in playground:

    playground exemple

    You will only have one layer this way