Tuesday, 27 January 2009

Drawing in views

For the people lookin for information on how to draw for the iPhone must look here

Drawing in Cocoa is simple (NOT).

In fact each object on the screen can be seen as a view and each view has a method named drawRect: (Rect) that is called each time when a view need to be (re)drawn. For example in the case of a resize, a maximize window etc.

Most people will then use a path to do the actual drawing (by using an instance of the class NSBezierPath).

Now a simple example to show how to draw in Cocoa.

First start a new project and open the Interface Builder. From the controls window , select the 5th item (this contains custom view, image view etc).
Click on custom view and drag it to the window :

Now in XCode you have to define a class which will be associated with this custom view.
You do this by selecting XCode>File>New File, then a popup will show in which you select 'objective-c class subclass NSView'.

Give your new class a name, when you open the .m file you'll see that XCode generated 2 methods : drawRect and initWithFrame.

Now go back to the Interface Builder and drag the .h file from you freshly created class to the MainMenu.nib window. By doing this you have informed the interface builder that their is a new view class.

In a last step you have to associate the CustomView with the view class.

You do this by opening an Inspector on the customview and changing the custom class.

So now we are done in the IB, save and close it. And do a build and go.

And you see an empty window, of course because we didn't do anything yet.

To actually draw something you have to implement the drawRect method of your custom view class :

// Drawing code here.

// Set the color in the current graphics context for future draw operations
[[NSColor blackColor] setStroke];
[[NSColor yellowColor] setFill];

// Create our drawing path

NSBezierPath* drawingPath = [NSBezierPath bezierPath];

// draw a rectangle

[drawingPath appendBezierPathWithRect: rect];

// actually draw it
[drawingPath stroke] ;

// and fill it
[drawingPath fill] ;


The above source code lines gives an example of what can be in a drawRect method.
What it does is in fact drawing a rectangle and fill it with color yellow.
Now as already said , each time an event happens to a view the drawRect method will be called for each view.

Sometimes we want to draw a grid, some explanation and source code can be found here ,
I also looked at the different ways to draw rectangles.

No comments:

Post a Comment