Color of CGPoint changes all lines and should only change new lines

My code uses to classes. When the function dizzy is called it changes the color of all the lines in the uiview. What I want it to do is only change lines colors that are drawn after the function is called. It should not change the color of the lines that are already drawn like it does now.

class ViewController: UIViewController {
@objc func dizzy() {
     canvas.strokeColor = .gray

}

 var canvas = Canvas()
 }
  class Canvas: UIView {

    var strokeColor = UIColor.green {
          didSet {
              self.setNeedsDisplay()
          }
      }

func undo() {
    _ = lines.popLast()
    setNeedsDisplay()
}

func clear() {
    lines.removeAll()
    setNeedsDisplay()
}




var lines = [[CGPoint]]()

override func draw(_ rect: CGRect) {
    super.draw(rect)

    guard let context = UIGraphicsGetCurrentContext() else { return }

   context.setStrokeColor(strokeColor.cgColor)
    context.setLineWidth(5)
    context.setLineCap(.butt)

    lines.forEach { (line) in
        for (i, p) in line.enumerated() {
            if i == 0 {
                context.move(to: p)
            } else {
                context.addLine(to: p)
            }
        }
    }

    context.strokePath()

}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    lines.append([CGPoint]())
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let point = touches.first?.location(in: self) else { return }
    guard var lastLine = lines.popLast() else { return }
    lastLine.append(point)
    lines.append(lastLine)
    setNeedsDisplay()
}

}

@timswift Do you still have issues with this?

hi @timswift,
that is because you need to set/tag the colour for every line drawn.

instead of just having an array of CGPoint, you need to have a structure that saves the points and the color that is used at that time. So when you redraw, it should update accordingly and change colour.

cheers,

issue resolved thanks for your help.

hi @timswift,

good to hear that

cheers,

This topic was automatically closed after 166 days. New replies are no longer allowed.