Supporting SwiftUI with Core Graphics

Nov 22 2022 Swift 5.5, iOS 15, Xcode 13

Part 1: Supporting SwiftUI with Core Graphics

5. Drawing with Pencil

Episode complete

Play next episode

Next
Save for later
About this episode
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 4. Build a UIKit Drawing Pad Next episode: 6. Shading with Pencil

This video Drawing with Pencil 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 kodeco.com Professional subscription.

To test the code in this video and the next one, you’ll need an Apple Pencil and a recent iPad that supports it. You can skip this video if you don’t have them, and just use the touch drawing pad for the rest of the course.

private let defaultLineWidth: CGFloat = 6
private let minLineWidth: CGFloat = 5
private let forceSensitivity: CGFloat = 4
var lineWidth = defaultLineWidth
if touch.force > 0 {
  lineWidth = touch.force * forceSensitivity
}

Coalesced Touches

In the SwiftUI drawing pad, we replaced the stroke after drawing it with a Bezier spline which smoothed out the curve, but Pencil has a clever way of capturing touches that are lost when you drag fast.

var touches: [UITouch] = []
if let coalescedTouches = event?.coalescedTouches(for: touch) {
  touches = coalescedTouches
}
if let coalescedTouches = event?.coalescedTouches(for: touch) {
  touches = coalescedTouches
} 🟩else {
  touches.append(touch)
}
print("Touch count: ", touches.count)
for touch in touches {
  drawStroke(context: context.cgContext, touch: touch)
}