Thursday, 12 February 2009

Drawing in views : how to draw a grid ?

Drawing a grid in a view is rather simple, I do this often to better align my objects.
To draw a grid you can simply add the following lines of code to your drawRect: method :

(GRIDSIZE is a macro defined in the .h file of the view).

- (void)drawRect:(NSRect)rect {
// Drawing code here.
int width = rect.size.width ;
int height = rect.size.height ;

int i = 0 ;

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

// Create our drawing path

NSBezierPath* drawingPath = [NSBezierPath bezierPath];

// Draw a grid
// first the vertical lines
for( i = 0 ; i <= width ; i=i+GRIDSIZE ) { [drawingPath moveToPoint:NSMakePoint(i, 0)]; [drawingPath lineToPoint:NSMakePoint(i, height)]; } // then the horizontal lines
for( i = 0 ; i <= height ; i=i+GRIDSIZE ) { [drawingPath moveToPoint:NSMakePoint(0,i)]; [drawingPath lineToPoint:NSMakePoint(width, i)]; } // actually draw the grid
[drawingPath stroke];

 

}

No comments:

Post a Comment