Drawing in Obj-C: Lines and Circles

Day 14

In a previous post I showed an example of creating a custom view in which I drew a triangle on screen. I thought I’d spend a bit of time taking a closer look at the code and demonstrate how to draw simple shapes in Objective-C.

Example 1: Lines

The following will draw a triangle in the view with green fill and a red stroke. I’ve added a bunch of comments to each line to make it clear what is happening.

The above will draw something like below:

Example 2: Circles

Next I’ll draw a red circle. Again I’ve added some comments for each line.

The above will produce:

Using Convenience Methods for Drawing

Say I want to make 3 circles on the screen, each of them with a slightly smaller radius. Well, I could simply copy and paste the code for making a circle 3 times, but it would be better if I could write a single drawCircle: method that will make one for me 3 times.

In my drawRect: I would do something like this:

Note I’m grabbing the current context first before calling the circle drawing method with:

This is important and must be called within drawRect:. Then, I am calling a new method three times, each with a slightly smaller radius:

The drawCircleInContext:withRadius: method would look something like this:

The bulk of the code will be the same as before, but at the top of the method you’ll want to add:

This will ensure the context you’re using is the current one. Then at the bottom of the method (after drawing the circle) you should add:

This will remove the current context from the stack and restore it to what it was before.

If all went well, you should end up with this:

Re-Drawing

I mentioned this in my post about Custom Sub Views, but it’s worth repeating. If you want to change the appearance of your drawing, it might seem logical to call drawRect: from your master view or controller in order to re-draw.

Don’t do it!

You should never call drawRect: directly. Instead you should use setNeedsDisplay, like so:

Assuming self.myCanvas is your UIView that does the drawing, the above line lets the system know that you want to redraw the myCanvas view (you could also call setNeedsDislay within the UIView class itself, of course). As soon as it is ready the view will be updated.

Here’s an example of how you might trigger this from a view controller:

Download Project File

In case it helps I’ve made the Xcode project fie available to download below. The app produces either a triangle or circle depending on which button you tap.

Download ShapesApp.zip