How to draw a line on iPhone?

I am starting to program on the iPhone and want to draw a line on the phone screen for the purpose of learning using Quartz and UIKit.

How to start drawing?

+43
iphone cocoa-touch quartz-graphics
May 13 '09 at 6:20
source share
2 answers

The first step is to define a subclass of UIView, create a space for drawing.

If you are starting with a new application, the easiest way is to start with the "Window-based application" template.

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

Now open the Resources group and double-click MainWindow.xib to open it in Interface Builder. From here you will see a window called "Window." Press Cmd + Shift + L to open the library and drag the View component into your window and position it so that you can see it. When you have selected a new view, press Cmd + 4 to open the Identity Inspector and in the "Identity Class" section, select the drop-down list and select MyView.

Then you need to implement the drawRect: method in MyView.m, here is an example of 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", now you should see a red line on the iPhone.

For more information on Core Graphics, see the Apple documentation. I also found it useful to look for functions starting with CGContext in the Xcode documentation viewer and view them — most of the Core Graphics functions that you end up using will begin with the term “CGContext”.

+147
May 13 '09 at 9:19 a.m.
source share
— -

You can also draw a line using UIBezierPath . A horizontal line with a vertical orientation will be built below:

 - (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]; } 
+4
Jul 21 '14 at 5:53
source share



All Articles