MobileEntityLogo.png

Hi.

Welcome to the best online resource for IOS & Android tutorials.

How to add apple pencil functionality to your app using PencilKit

How to add apple pencil functionality to your app using PencilKit

Their aren’t many PencilKit starter tutorials out their. Other websites want to charge for PencilKit tutorials. You have come to the right place to learn the basics of PencilKit. PencilKit allows for apple pencil functionality such as native color and pen thickness pickers. Lets get started.

Your app will look like the image below.

PencilKit in action

The code that creates the canvas

Canvas Code

Canvas Code

This code snippet defines our canvas, the area you use to draw using your Apple Pencil.

Line 14 defines the view for our canvas. The view is of type PKCanvasView which is part of the PencilKit API.

Our canvas code goes inside our ViewDidLoad because we want it to be displayed as soon as the app opens. Line 19 disables a constraint feature that we will not need because it interferes with the apple pencil.

Line 20 just adds our canvas view to the root View.

Line 21 sets the background color to white, by default our canvas has a background of black.

Lines 23 through 30 set the constraints for the canvas, you may set the constraints to your own preference however these constraints set the canvas to fill the root view.

Now lets work on the tool picker view.

The code that creates the tool picker view

Tool picker code

Tool picker code

The code above is what creates the tool picker. The tool picker is what allows you to chose between paint brushes, colors, thickness, etc. This is baked into the PencilKit API making it simple to create a basic canvas with tools to play with.

We have this code inside a ViewDidAppear because we want to append the tools view to the canvas, and if we call it in the ViewDidLoad the tools would hide behind the canvass.

Our tools code is inside a guard statement to prevent unwanted exceptions to be thrown.

Line 35 is just a shortcut function to our window saving code space. Line 36 is the view for the tools picker. The tools picker is a PKToolPicker which is part of the PencilKit API.

Line 38 we set the toolPicker to visible, making it show when loading the view.

line 39 allows for the toolPicker and canvas to communicate with each other.

Line 40 alerts the canvas on tool picker changes.

How to add placeholders manually to your swift code

How to add placeholders manually to your swift code

How to create functions with optional parameters in Swift

How to create functions with optional parameters in Swift

0