Vincent Tourraine
Blog

Notes WWDC 2019 : Introducing PencilKit

#dev #iOS

Référence : Session 221 - Introducing PencilKit

Pencil on iPad, new in iOS 13:

Great pencil experiences

Support Pencil Taps

let interaction = UIPencilInteraction() interaction.delegate = self view.addInteraction(interaction)
func pencilInteractionDidTap(_ interaction: UIPencilInteraction) { 
  switch UIPencilInteraction.preferredTapAction {
    // ...
  }
}

PencilKit

let canvas = PKCanvasView(frame: bounds)
view.addSubview(canvas)
canvas.tool = PKInkingTool(.pen, color: .black, width: 30)

Thumbnail Generation

On background queue, take Dark Mode into account (via trait collection):

func thumbnail(drawing: PKDrawing, thumbnailRect: CGRect, traitCollection: UITraitCollection) {
  thumbnailQueue.async {
    traitCollection.performAsCurrent {
      let image = drawing.image(from: thumbnailRect, scale: 2.0)
    }
  }
}

Set a tool

canvasView.tool = PKInkingTool(.pen, color: .blue, width: 10)

PKToolPicker

let toolPicker = PKToolPicker.shared(for: window)
toolPicker.addObserver(canvasView)
toolPicker.setVisible(true, forFirstResponder: canvasView) canvasView.becomeFirstResponder()

Compact style:

Customize content scrolling: var allowsFingerDrawing: Bool { get set } (true by default)

Drawing over content:

canvasView.opaque = false
canvasView.backgroundColor = .clear

Force user interface style, for instance if writing over an image or a PDF:

canvasView.overrideUserInterfaceStyle = .light

Markup everywhere

Set a screenshot delegate on UIWindowScene

class DrawingViewController: UIScreenshotServiceDelegate {
  override func viewWillAppear() {
    super.viewWillAppear()
    view.window.windowScene.screenshotService.delegate = self
  }
}

Deliver full content as PDF data, with 2 metadata info:

func screenshotService(
UIScreenshotService,
generatePDFRepresentationWithCompletion: (Data?, Int, CGRect) -> Void)