How to Draw Shapes with Core Graphics

Matthew Campbell, August 19th, 2009

Would you like to know how to draw simple shapes directly on your iPhone app screen?

Most of the time we rely on UIKit to draw the images we use for our controls like buttons and other user controls. However, there are times when we would like to draw our own shapes or even let our users draw shapes on the screen. The technology that you use for this is called Core Graphics.

Core Graphics uses the idea of a context which is like an artist’s palate where we will do our drawing. When you draw with Core Graphics you must first define a color and width for a virtual pen and then give the pen instructions to move around the screen. Once you have done this you may call function that will execute your instructions and draw the line or shape.

The easiest way to experiment with using Core Graphics is to add a new UIView to your XCode project and then to add the view to a view controller. All the Core Graphics code must be located in the UIView implementation file (don’t confuse this with a view controller).

In my example project I first added a new UIView called CGView and then assigned an instance of this view to my view controller’s view property. Here is the relevant code from my view controller:

The easiest place to add the code the does the drawing in your UIView subclass is the drawRect method. Here is some example code I put in there that draws some lines and a rectangle. See the embedded comments for detailed explanations of what each line of code is doing:

When I build and run this project the output will look like this:

That is how to draw shapes – there are many other features to Core Graphics so be sure to check out the documentation on the Apple website.