我的代码用于类。当函数 dizzy 被调用时,它会改变 uiview 中所有线条的颜色。我想要它做的只是改变调用函数后绘制的线条颜色。它不应该像现在这样改变已经绘制的线条的颜色。
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()
}
}