Supporting SwiftUI with Core Graphics

Nov 22 2022 Swift 5.5, iOS 15, Xcode 13

Part 1: Supporting SwiftUI with Core Graphics

4. Build a UIKit Drawing Pad

Episode complete

Play next episode

Save for later
About this episode
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 3. Host a UIView in a SwiftUI View Next episode: 5. Drawing with Pencil

This video Build a UIKit Drawing Pad was last updated on Nov 22 2022

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a Professional subscription.


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

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.move(to: previousLocation)
context.addLine(to: location)
drawStroke(context: context.cgContext, touch: touch)
override func draw(_ rect: CGRect) {
  drawingImage?.draw(in: rect)


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.


Go back CanvasView and at the end of touchesMoved, call setNeedsDisplay.



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.