цвет cgpoint меняет все строки и должен менять только новые - PullRequest
0 голосов
/ 28 октября 2019

Мой код используется для классов. Когда вызывается головокружительная функция, она меняет цвет всех линий в окне просмотра. Я хочу только изменить цвет линий, которые рисуются после вызова функции. Он не должен менять цвет линий, которые уже нарисованы, как сейчас.

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()
}

}

1 Ответ

0 голосов
/ 28 октября 2019

Вам нужно создать struct для хранения цвета с линией. В touchesBegan() сохраните текущий strokeColor с coloredLine. В draw(rect:) для каждой строки установите context.setStrokeColor(line.color.cgColor) перед штриховкой.

Я проверил это, добавив кнопки для изменения цвета. Вы можете подключить его, как считаете нужным.

struct ColoredLine {
    var color = UIColor.black
    var points = [CGPoint]()
}


class ViewController: UIViewController {

    @IBOutlet weak var canvas: Canvas!

    @IBAction func doRed(_ sender: UIButton) {
        canvas.strokeColor = .red
    }

    @IBAction func doGreen(_ sender: UIButton) {
        canvas.strokeColor = .green
    }

    @IBAction func doBlue(_ sender: UIButton) {
        canvas.strokeColor = .blue
    }

    @IBAction func doBlack(_ sender: UIButton) {
        canvas.strokeColor = .black
    }

 }


class Canvas: UIView {

    var strokeColor = UIColor.green

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

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

    var lines = [ColoredLine]()

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

        guard let context = UIGraphicsGetCurrentContext() else { return }

        context.setLineWidth(5)
        context.setLineCap(.butt)

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

            context.setStrokeColor(line.color.cgColor)
            context.strokePath()
            context.beginPath()
        }


    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        var coloredLine = ColoredLine()
        coloredLine.color = strokeColor
        lines.append(coloredLine)
    }

    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.points.append(point)
        lines.append(lastLine)
        setNeedsDisplay()
    }

}
...