How do I draw a line on the iPhone?

anish picture anish · May 13, 2009 · Viewed 52.1k times · Source

I am a beginner at iPhone programming, and would like to draw a line to the phone screen for the purpose of study using Quartz and UIKit.

How do I start drawing?

Answer

Tobias Cohen picture Tobias Cohen · May 13, 2009

The first step is to define a subclass of UIView, to create a space to draw in.

If you're starting with a new application, the easiest way will be to start with the "Window-based application" template.

Then go New File and create an "Objective-C Class" with "Subclass of" set to "UIView", and give it a name, say MyView.m.

Now open up the "Resources" group and double click on "MainWindow.xib" to open it in Interface Builder. From here you should see a window named "Window". Hit Cmd+Shift+L to bring up the Library, and drag a "View" component onto your window, and position it so you can see all of it. With your new View selected, hit Cmd+4 to bring up the Identity Inspector and under "Class Identity", click the dropdown and choose MyView.

Next, you need to implement the drawRect: method in MyView.m, here's some example code that draws a line:

- (void)drawRect:(CGRect)rect {
    CGContextRef c = UIGraphicsGetCurrentContext();

    CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
    CGContextSetStrokeColor(c, red);
    CGContextBeginPath(c);
    CGContextMoveToPoint(c, 5.0f, 5.0f);
    CGContextAddLineToPoint(c, 50.0f, 50.0f);
    CGContextStrokePath(c);
}

Save everything and click "Build and Run", you should now see a short red line on the iPhone.

For more information about Core Graphics, look up the Apple Documentation. I've also found it helpful to search for functions beginning with CGContext in the Xcode documentation viewer, and browse through those - most of the Core Graphics functions you'll end up using will start with the term "CGContext".