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”.
Tobias Cohen May 13 '09 at 9:19 a.m. 2009-05-13 09:19
source share