O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

20.6. Drawing Lines

Problem

You simply want to be able to draw lines on a graphics context.

Solution

Retrieve the handle to your graphics context and then use the CGContextMoveToPoint and the CGContextAddLineToPoint functions to draw your line.

Discussion

When we talk about drawing shapes in iOS or OS X, we are implicitly talking about paths. What are paths, you may ask? A path is constructed from one or more series of points drawn on a screen. There is a big difference between paths and lines. A path can contain many lines, but a line cannot contain many paths. Think of paths as series of points—it’s as simple as that.

A button is displayed on the screen with a stretchable background image

Figure 20-16. A button is displayed on the screen with a stretchable background image

Lines have to be drawn using paths. Specify the start and end points, and then ask Core Graphics to fill that path for you. Core Graphics realizes that you have created a line on that path and will paint that path for you using the color that you specified (see Recipe 20.3).

We will be talking about paths in more depth later (see Recipe 20.7), but for now let’s focus on using paths to create straight lines. To do this, follow these steps:

  1. Choose a color on your graphics context (see Recipe 20.3).

  2. Retrieve the handle to the graphics context, using the UIGraphicsGetCurrentContext function.

  3. Set the starting point for your line using the CGContextMoveToPoint procedure.

  4. Move your pen on the graphics ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required