Pencilkit iOS Swift

BN
iOS World
Published in
2 min readJan 17, 2023
Photo by Ave Calvar on Unsplash

PencilKit is a frame introduced by Apple in iOS 13 that allows inventors to add support for Apple Pencil input to their apps. It provides a set of APIs and stoner interface rudiments that can be used to produce delineation and note-taking gests that are analogous to Apple’s own Notes and Post apps.

Then are some features and generalities of PencilKit:

  1. PKCanvasView, This is the main view that provides the delineation face for PencilKit. You can use this view to add a delineation face to your app, and it automatically handles the input from an Apple Pencil.
  2. PKToolPicker, This is a view that provides a toolbar for opting different tools, similar as pencils, pens, and erasers. You can use this view to give a stoner interface for switching between different tools in your app.
  3. PKInkingTool, This is a tool that provides support for drawing with an Apple Pencil. You can use this tool to customize the appearance and behavior of the pencil, similar as the range, color, and blending mode.
  4. PKDrawing, This is a class that represents the delineation data. You can use this class to load and save delineations, and it also provides styles for manipulating the delineation data, similar as undo and redo.
  5. PKToolPickerObserver This protocol is used to observe the changes of tool chooser and its named tool.

To apply PencilKit in your app, you’ll need to add the PencilKit framework to your design and use the classes and styles handed by the frame to handle the input from an Apple Pencil and display the delineation face.

Sample code for initialize PencilKit:

import PencilKit

class ViewController: UIViewController {

var canvasView: PKCanvasView!
var toolPicker: PKToolPicker!
var drawing: PKDrawing!

override func viewDidLoad() {
super.viewDidLoad()

// Create the canvas view
canvasView = PKCanvasView(frame: view.bounds)
view.addSubview(canvasView)

// Load the drawing from a file
if let url = Bundle.main.url(forResource: "drawing", withExtension: "drawing") {
do {
let data = try Data(contentsOf: url)
drawing = try PKDrawing(data: data)
canvasView.drawing = drawing
} catch {
print("Error loading drawing: \(error)")
}
}

// Create the tool picker
toolPicker = PKToolPicker.shared(for: .touch)
toolPicker.setVisible(true, forFirstResponder: canvasView)
toolPicker.addObserver(canvasView)
}

func saveDrawing() {
do {
// Get the drawing data
let data = try drawing.dataRepresentation()

// Save the drawing to a file
let documentsURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = documentsURL.appendingPathComponent("drawing.drawing")
try data.write(to: fileURL)

print("Drawing saved to \(fileURL)")
} catch {
print("Error saving drawing: \(error)")
}
}
}

--

--