Custom Drawing

You will sometimes need to do some of your own drawing, for example when building a custom button shape. To do this, you just need to subclass UIView and override the - (void)drawRect:(CGRect)aRect; method.

You should never call drawRect: directly. Instead, you call - (void)setNeedsDisplay;, which tells your view to call drawRect: when it’s ready to do so.

Core Graphics Framework

Drawing is achieved using the Core Graphics framework (also sometimes referred to as Quartz 2D). Core Graphics is written in pure C, meaning that it’s not object-oriented and that it doesn’t work with Objective-C syntax (no brackets).

First, you get a context to draw into. The context determines where your drawing goes. This is usually the screen, but can also be a PDF, a printer, etc.

Then, you create paths using lines, arcs, etc. This is similar to drawing shapes in Processing, Flash, and everything else; you just have a sequence of move to, line to, arc to statements.

Next, you set colors, line widths, line caps, etc.

Finally, you render the paths created above.

Here is that same code in a UIView subclass.

Instead of drawing lines all around, you can simply close the shape when you’re done.

You can also build a shape using a CGRect. Note that if you want to render the fill and stroke, you must do so in two steps.

To render circles and ellipses, you must use a CGRect.

It is sometimes easier to use the - (void)setFill and - (void)setStroke methods in UIColor to set your colours.

There are many more functions available to customize your drawing. You can find them all in the CGContext Reference.

  1. Quartz 2D Programming Guide. Apple, Visited Sep 24 2012.

Comments are closed.