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

About this episode
Leave a rating/review
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

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Pro subscription. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

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.


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.