Repository Public
1// SP Notes iOS2// File: Features/Drawing/ShapeSnapping.swift3// Description: Smart shapes on a PencilKit canvas: reads the points of the stroke just drawn, asks `ShapeRecognizer`, and builds the4// clean shape as PencilKit strokes with the same ink and width as the hand-drawn one.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import PencilKit9import UIKit1011enum ShapeSnapping {12 /// The centre line of a stroke as drawn (its transform applied).13 static func points(of stroke: PKStroke) -> [CGPoint] {14 stroke.path.interpolatedPoints(by: .parametricStep(0.5)).map { $0.location.applying(stroke.transform) }15 }1617 /// The drawing with its last stroke replaced by the shape it draws; nil when the last stroke is not a shape.18 static func snappingLastStroke(of drawing: PKDrawing, options: ShapeRecognizer.Options = .standard) -> (drawing: PKDrawing, match: ShapeMatch)? {19 guard let last = drawing.strokes.last, last.mask == nil, let match = ShapeRecognizer.recognize(points(of: last), options: options) else { return nil }20 var strokes = drawing.strokes21 strokes.removeLast()22 strokes.append(contentsOf: self.strokes(for: match.shape, like: last))23 return (PKDrawing(strokes: strokes), match)24 }2526 /// The shape as strokes: same ink, a constant width (the median width of the hand-drawn stroke).27 static func strokes(for shape: RecognizedShape, like original: PKStroke) -> [PKStroke] {28 let scale = sqrt(abs(original.transform.a * original.transform.d - original.transform.b * original.transform.c))29 let samples = Array(original.path.interpolatedPoints(by: .parametricStep(1)))30 let widths = samples.map { max($0.size.width, $0.size.height) * scale }.sorted()31 let width = widths.isEmpty ? 4 : widths[widths.count / 2]32 let opacity = samples.isEmpty ? 1 : samples.map(\.opacity).reduce(0, +) / CGFloat(samples.count)33 return shape.outlines.map { outline in34 PKStroke(ink: original.ink, path: PKStrokePath(controlPoints: controlPoints(outline, sharp: shape.hasCorners, width: width, opacity: opacity), creationDate: Date()))35 }36 }3738 /// Control points of a B-spline that follows the polyline: a point every 2 pt along each side, and each corner three times39 /// (a triple control point makes the curve pass through it with a sharp angle).40 static func controlPoints(_ outline: [CGPoint], sharp: Bool, width: CGFloat, opacity: CGFloat) -> [PKStrokePoint] {41 var locations: [CGPoint] = []42 for (index, vertex) in outline.enumerated() {43 if index > 0 {44 let previous = outline[index - 1], length = hypot(vertex.x - previous.x, vertex.y - previous.y)45 let pieces = max(1, Int((length / 2).rounded(.up)))46 if pieces > 1 { for k in 1..<pieces { let t = CGFloat(k) / CGFloat(pieces); locations.append(CGPoint(x: previous.x + (vertex.x - previous.x) * t, y: previous.y + (vertex.y - previous.y) * t)) } }47 }48 let isEnd = index == 0 || index == outline.count - 149 locations.append(contentsOf: Array(repeating: vertex, count: sharp && !isEnd ? 3 : 1))50 }51 return locations.enumerated().map { index, location in52 PKStrokePoint(location: location, timeOffset: Double(index) * 0.002, size: CGSize(width: width, height: width), opacity: opacity, force: 1, azimuth: 0, altitude: .pi / 2)53 }54 }55}56