Monday 2 March 2009

Drawing in views: rectangles

When you want to draw a rectangle (or fill one), you basically have 2 choices :

1. You want absolute performance and less accuracy then you can use the functions defined in NSGraphics.h (NSFrameRect, NSRectFill etc).

2. You need absolute accuracy and don't care so much about performance then you can use the methods defined in NSBezierPath.

(the reason why the NSBezierPath is less performant is explained in this article ).

The following code extract is from a drawRect: method of a custom view :
It shows the different methods of drawing and filling a rectangle.

NSBezierPath *aPath ;

NSBezierPath *myPath ;

// reset the bounds
[self setBounds: NSMakeRect(0,0,1000,1000)] ;

//---------------------------------
//1. filling rectangles
//---------------------------------
[[NSColor grayColor] set] ;

// convenience method for filling a rectangle
// less precise , but good performance
// C functions defined in NSGraphics.h
NSRectFill( rect ) ;

// filling a rectangle using a class method of NSBezierPath
[NSBezierPath fillRect: NSMakeRect( 0,500,75,75) ] ;


// filling a rectangle using an instance method of NSBezierPath
// this usefull if you want to do additional drawing in that path
myPath = [NSBezierPath new] ;
[myPath appendBezierPathWithRect: NSMakeRect ( 600,0,80,80) ] ;
[myPath fill] ;


// -----------------------------
//2. drawing a rectangle
//------------------------------

[[NSColor redColor] set ] ;

// drawing a rectangle using a class method of NSBezierPath
[NSBezierPath strokeRect: NSMakeRect( 500,500,80,80 ) ] ;

// drawing a rectangle using an instance method of NSBezierPath
// this usefull if you want to do additional drawing in that path
[[NSColor greenColor] set ] ;
aPath = [NSBezierPath bezierPathWithRect: NSMakeRect( 450,600,100,100) ] ;
[aPath stroke] ;


// absolute performance, less precise
// C functions defined in NSGraphics.h
NSFrameRectWithWidth( NSMakeRect( 700,700,70,70), 10 ) ;

NSFrameRect( NSMakeRect( 0,700,80,80 ) );

No comments:

Post a Comment