Wednesday, April 25, 2012

Template program to learn Cocoa graphics

The standard way to learn new programming language is very boring for me - endless reading of heavy books, typing useless programs that calculates factorials,... Since my student times, since GWBASIC I begin from the graphics, simple graphic, rectangles, circles - the graphic primitives. When I know how to draw them, I can go on and learn the basic language constructions, language semantic and programming techniques.
This way works for me in my Cocoa period. In this post I'd like to show two methods to create a template project that allows to learn the Cocoa graphical primitives. This template can grow in your hands and become a real Cocoa (or Coco Touch) application.
As any Cocoa application this application has a main window and a view inside. That's all. First method uses Interface Builder. The second one fully ignores the Interface Builder.


Method with Interface Builder.
1. Create new project in Xcode from the Cocoa Application template, add new Objective-C class derived from NSView, give a name to this class, for example DrawingView.
2. Launch Interface Builder by pressing on the MainMenu.xib file. Find "custom view" in the Library, drag and drop it onto the application window. Set the view size - almost the whole window. In the Size Inspector (Cmd+3) set the autosizing options. In the Identity Inspector (Cmd+6) set the view name as DrawingView. Save the project (Ctrl+S).
3. Switch to Xcode and open DrawingView.m file. In -drawRect method we can add our drawing code. For example:
- (void)drawRect:(NSRect)dirtyRect {
    // Drawing code here.
    
    [NSGraphicsContext saveGraphicsState];
    
    NSRect rect = NSInsetRect([self bounds], 5, 5 );
    [[NSColor blueColor] set];
    NSRectFill( rect );
    
    [NSGraphicsContext restoreGraphicsState];
}
The application runs:

Method without Interface Builder.
1. The first item is the same - create new project in Xcode from the Cocoa Application template, add new Objective-C class derived from NSView.
2. Open the implementation of the application delegate class (AppDelegate.m) and create the view object in the launching method:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application 
    DrawingView *view = [[DrawingView alloc] 
                         initWithFrame: [self.window.contentView bounds]];
    [self.window.contentView addSubview: view];
    [view setAutoresizingMask: ( NSViewWidthSizable | NSViewHeightSizable) ];
    [view release];
}
3. Open the view implementation class and add the drawing code.
Launch the application.

No comments:

Post a Comment