This video Build a UIKit Drawing Pad was last updated on Nov 22 2022
CanvasView.swift
With our architecture all set up, we’re ready to get to work on the drawing magic here in CanvasView.swift. We’ll use a method called touchesMoved. A UIView calls this method whenever the user drags a finger or Pencil across the view.
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
}
drawingImage = UIGraphicsImageRenderer(size: bounds.size).image { context in
}
UIColor.white.setFill()
context.fill(bounds)
drawingImage?.draw(in: bounds)
private func drawStroke(context: CGContext, touch: UITouch) {
}
let previousLocation = touch.previousLocation(in: self)
let location = touch.location(in: self)
let lineWidth: CGFloat = 5
context.setLineWidth(lineWidth)
context.setLineCap(.round)
color.setStroke()
context.move(to: previousLocation)
context.addLine(to: location)
context.strokePath()
drawStroke(context: context.cgContext, touch: touch)
override func draw(_ rect: CGRect) {
drawingImage?.draw(in: rect)
}
DrawingPadView.swift
Open DrawingPadView.swift to check out our drawing so far. If we preview this and draw, nothing happens. The view isn’t calling that draw method when the drawing image changes.
CanvasView.swift
Go back CanvasView and at the end of touchesMoved, call setNeedsDisplay.
setNeedsDisplay()
DrawingPadView.swift
Go back to DrawingPadView.swift and try it out again in the preview. You may need to clean and build before it works. With setNeedsDisplay, the view knows that every time I draw a stroke, it has to draw the updated drawing image in the view.