Supporting SwiftUI with Core Graphics

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

Part 1: Supporting SwiftUI with Core Graphics

05. Drawing with Pencil

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: 04. Build a UIKit Drawing Pad Next episode: 06. Shading 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

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)
}