How do I draw a line on the iPhone?

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".


You can also draw a line using UIBezierPath. The following will draw a vertically-centered horizontal line:

- (void)drawRect:(CGRect)rect {
    CGFloat rectHeight = CGRectGetHeight(rect);
    CGFloat rectWidth = CGRectGetWidth(rect);

    UIBezierPath *line = [UIBezierPath bezierPath];
    [line moveToPoint:CGPointMake(0, rectHeight / 2)];
    [line addLineToPoint:CGPointMake(rectWidth, rectHeight / 2)];

    [[UIColor lightGrayColor] setStroke];
    [line stroke];
}