Member-only story
Drawing in a UIView
How to draw with your finger and export an image

In this short article, we will explore how to add a view to our apps, where users can draw with their finger.
Creating a drawing is quite easy. First, we will see how to get the positions of touches and track movements. The next step is to connect these points in a CGContext
to get our drawing. Finally, we will see how to reset and export the created drawing as a UIImage
.
Getting the Location of Touches
We start by tracking the touches inside of the view.
// 1
— First, we create a reusable UIView
subclass to wrap the drawing function. In this class, we have an array of arrays containing CGPoint
s. The outer array represents lines, where each line consists of multiple points.
// 2
— Since this class is a subclass of UIView
, we can override the methods touchesBegan(_:with:)
and touchesMoved(_:with:)
, which allow us to get the location of touches. These methods have access to a set of touches, from which we can get the first touchpoint and convert it to the coordinate system of this view.
// 3
— Now that we have our point, we need to add it to lineArray
. Because touchesBegan
marks the start of a new line, we first append an empty array of CGPoint
s to it. Next, we add our first point to this new line.
// 4
— All following points will be tracked in touchesMoved
. Just like before, we access the current point and add it to our array. Finally, by calling setNeedsDisplay()
, we trigger a redrawing of our view.
We will see in the next method how we can draw our points.
Drawing the Lines
The next step is to draw the points to our view.