Search code examples
iosswiftuibezierpathcgcontext

UIBezierPath stroke redraws it multiple times in touchesMoved


I am implementing a coloring app in Swift 3.0 which uses UIBezierPath for touch to fill coloring style. In touchesBegan I create the path:

touchFillPath = UIBezierPath()

and in touchesMoved I stroke it for each new point:

touchFillPath.addLine(to: location)
touchFillPath.stroke()

but this results in the path stroked multiple times above the same area, and hence the selected color opacity changes.

I need to stroke the path for each touchesMoved call to allow the user to see the area colored while he is moving touches.

How can I stroke the same path multiple times without overriding the same area multiple times?


Solution

  • @joeybladb I have tried your solution, but it draws small segments for each 'touchesMoved' action.

    So to fix this, I save all points touched in an array:

    pathPoints.append(NSValue(cgPoint:location))
    

    and after calling touchFillPath.removeAllPoints(), I add all these points again to the path:

    for (index, element) in (pathPoints.enumerated())! {
       let point = element.cgPointValue
       if index == 0 {
           touchFillPath.move(to: point)
       } else {
           touchFillPath.addLine(to: point)
       }
    }
    

    so that the next time I call touchFillPath.stroke(), it strokes the whole path:

    touchFillPath.move(to: lastPoint)
    touchFillPath.addLine(to: location)
    touchFillPath.stroke()