Swift中如何清除Core Graphics Context绘制的内容?
解决方案
要实现清除绘制内容的功能,核心是清空存储线条数据的数组并触发视图重绘,具体步骤如下:
1. 给CanvasView添加清除方法
在CanvasView类中新增一个公共的清除方法,用于清空线条数组并通知视图重绘:
struct Line { var points: [CGPoint] var strokeColor: UIColor var strokeWidth: CGFloat } class CanvasView: UIView { private var lines: [Line] = [] private var strokeWidth: CGFloat = 8.0 private var strokeColor: UIColor = .white // 新增清除方法 func clear() { lines.removeAll() setNeedsDisplay() } override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } lines.forEach { line in context.setStrokeColor(line.strokeColor.cgColor) context.setLineWidth(line.strokeWidth) context.setLineCap(.round) for (index, point) in line.points.enumerated() { if index == 0 { context.move(to: point) } else { context.addLine(to: point) } } context.strokePath() } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let point = touches.first?.location(in: self) else { return } let newLine = Line(points: [point], strokeColor: strokeColor, strokeWidth: strokeWidth) lines.append(newLine) setNeedsDisplay() } 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() } }
2. 绑定清除按钮的点击事件
在包含CanvasView的视图控制器中,给清除按钮添加点击事件,调用CanvasView的clear()方法:
class ViewController: UIViewController { // 通过IBOutlet关联你的CanvasView实例 @IBOutlet weak var canvasView: CanvasView! override func viewDidLoad() { super.viewDidLoad() } // 清除按钮的点击响应方法 @IBAction func clearButtonTapped(_ sender: UIButton) { canvasView.clear() } }
原理说明
你的绘制逻辑完全依赖lines数组中的数据——draw(_:)方法会遍历数组内的每一条线完成绘制。清空数组后调用setNeedsDisplay(),会触发视图重新执行draw(_:)方法,此时数组为空,自然不会绘制任何线条,视图就恢复到初始的清空状态。
内容的提问来源于stack exchange,提问作者Deltrin Sam
相关产品推荐
相关产品推荐

