Simple Introduction to Pencilkit: draw on an image! with zoom in and out features

Chloe Lee
2 min readJun 29, 2022

--

Hello, this is Chloe again. I would like to introduce ‘Pencilkit’ on UIKit. Pencilkit works perfectly with UIKit because its PKCanvasView is designed to be placed on top of UIScrollView.

I wished to make a zoomable, scrollable, and drawable module with an image in the background so that the image zooms and scrolls with the handwriting concurrently.

Captured Image of Simulator

You can find the full code of this module in the link below ⬇️

1. Set a Scrollable and Zoomable Module View

  • Set the initalizer with leadingScale, widthScale, and heightScale each indicating the ratio relative to the whole screen.
  • Keep the module within the bounds of the screen.
  • To make the screen look identical in portrait and landscape mode, check the orientation of the UIDevice and change the layout each time screen rotation is invoked. Specify a new array variable that contains NSLayoutConstraint to find out the exact constant to the anchor. This would enable the module to maintain the same size ratio in the landscape mode, but sometimes shorter, depending on the size of the image.

2. Add PKCanvasView as a Subview of the ModuleView

  • Allow the canvas view to scroll within the frame of the picture
  • Let the frame of the canvas view be the frame of the module
  • Set the zoomlevel to be the (screen’s height / screen’s width) in both orientations.

3. Set a Background Picture for Drawable CanvasView

  • Insert the image as the subview of the canvasView.
  • Let the picture’s width be the width of the module. Set it again when the screen is rotated.
  • If the module’s length is longer than the length of the item picture, resize the module’s frame, and if it’s shorter, make the picture scrollable within the module.

4. Add PKToolPicker to the View, which Hovers Over the Screen

5. Save and Load the Drawing using the UserDefaults Data

  • Create a storage class using UserDefaults. Sort, store, and recall with id for each case.
  • Save the drawing data each time the button is tapped.
  • Load the drawing data when toolkit is loaded.

6. Additional Feature) Multi ModuleView

  • Create a module class that inherits the UISrollView within the View Controller. Manage the modules with an array in ModuleScrollView. Most functions are defined in ModuleScrollView except for saving, screen rotation, and screen display.
  • Later created modules can be overlapped on top of the former module. Scroll, zoom, save, and drawing all works fine.

--

--