Code: iOS Freehand Drawing Part 1

There is some cases where we need to make a freehand drawing in our apps, for example to make a signature.

This will be the first part of three post that will allow you to draw in a freehand way.

Lets go!

1) Set up your project. If you don’t know how to start maybe it’s not your post.

newProyect

2) The main concept: we will create a custom subclass of UIView that will receive the inputs (touches) and then we will plot over it. So, left click and add a new file

NewFile

Select UIView as your main class and type some name.

subclass Uiview

3) The UIView subclass in deep:

The we will have a private interface where we have all the ivars that we need.

In the other hand the constructor will be:

The draw rect method: We need to set up the color and fill configuration’ for our bezier.

4) The core of the freehand: The touches events

To plot a line we will need several points, so how can i get this points?, easy, with “touches”.

touchFinger
we will need 4 methods for 4 states: touchBegan, touchMove, touchEnded and touchCancelled. Let’s see:

addLine

 

For each new point we will add a line to our path with  [path addLineToPoint:p]

We’re almost done, when the touches end we will need to close the path. (the last line will be created if you add your first point as the last to your path).

close path

5) Add this view your view controller view:

hierachy

That’s it, your custom view should looks like this:

examplegif

You can see the full code at: GitHub

No Comments Yet.

Write a Comment

Your email address will not be published. Required fields are marked *


7 − 5 =

Submitting this form, you agree with our Legal Notice and our Cookie Policy.