Supporting SwiftUI with Core Graphics

Nov 22 2022 · Swift 5.5, iOS 15, Xcode 13

Part 1: Supporting SwiftUI with Core Graphics

04. Build a UIKit Drawing Pad

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 03. Host a UIView in a SwiftUI View Next episode: 05. Drawing with Pencil

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

Take your career further with a Kodeco Personal Plan. 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.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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.