How do I draw a line on the iPhone?
Asked Answered
F

2

43

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?

Fremd answered 13/5, 2009 at 6:20 Comment(0)
A
146

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

Ance answered 13/5, 2009 at 9:19 Comment(3)
Can't plus you up enough willc2 and TobiasArmistead
Thank u so much. its very help to me.Nimmons
How to add blurring effect as touches move while drawing line?Moneybags
E
4

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];
}
Expectancy answered 21/7, 2014 at 5:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.