Created
January 13, 2012 22:14
-
-
Save chadmoone/1609043 to your computer and use it in GitHub Desktop.
NSObject drawing grid onto NSView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In View Class | |
- (void)drawRect:(CGRect)dirtyRect | |
{ | |
// Draw the background | |
NSGraphicsContext* theContext = [NSGraphicsContext currentContext]; | |
[theContext saveGraphicsState]; | |
[[NSGraphicsContext currentContext] setPatternPhase:NSMakePoint(0,[self.superview bounds].size.height)]; | |
[_backgroundColor set]; | |
NSRectFill([self bounds]); | |
[theContext restoreGraphicsState]; | |
[self drawPages]; | |
// Draw the grid | |
int gridY = grid.offset.y; | |
for (int i = 0; i < _numPages; i++) { | |
CGRect pageRect = CGRectMake(grid.offset.x, gridY, VBCanvasPageWidth, VBCanvasPageHeight); | |
// NSLog(@"fist grid X:%f Y:%f", pageRect.origin.x, pageRect.origin.y); | |
[grid drawRect:pageRect inView:self]; | |
gridY = gridY + VBCanvasPageHeight + VBCanvasPagePadding; | |
} | |
if (_isDragging) { | |
[[[NSColor redColor] colorWithAlphaComponent:0.3f] set]; | |
CGRect dragRect = CGRectMake(_downPoint.x, _downPoint.y, _upPoint.x - _downPoint.x, _upPoint.y - _downPoint.y); | |
NSRectFillUsingOperation(dragRect, NSCompositeSourceOver); | |
} | |
} | |
// In Object Class | |
- (void)drawRect:(CGRect)rect inView:(NSView *)view | |
{ | |
// NSLog(@"grid drawRect"); | |
if (!alwaysShown) { | |
// NSLog(@"not drawing grid"); | |
return; | |
} | |
// NSLog(@"drawing grid"); | |
// Figure out a big bezier path that corresponds to the entire grid. It will consist of the vertical lines and then the horizontal lines. | |
NSBezierPath *gridPath = [NSBezierPath bezierPath]; | |
NSInteger lastVerticalLineNumber = floor(NSWidth(rect) / spacing.doubleValue); | |
for (NSInteger lineNumber = 0; lineNumber <= lastVerticalLineNumber; lineNumber++) { | |
[gridPath moveToPoint:CGPointMake((lineNumber * spacing.doubleValue) + rect.origin.x, NSMinY(rect))]; | |
[gridPath lineToPoint:CGPointMake((lineNumber * spacing.doubleValue) + rect.origin.x, NSMaxY(rect))]; | |
} | |
NSInteger lastHorizontalLineNumber = floor(NSHeight(rect) / spacing.doubleValue); | |
for (NSInteger lineNumber = 0; lineNumber <= lastHorizontalLineNumber; lineNumber++) { | |
[gridPath moveToPoint:CGPointMake(NSMinX(rect), (lineNumber * spacing.doubleValue) + rect.origin.y)]; | |
[gridPath lineToPoint:CGPointMake(NSMaxX(rect), (lineNumber * spacing.doubleValue) + rect.origin.y)]; | |
} | |
// Draw the grid as one-pixel-wide lines of a specific color | |
[color set]; | |
[gridPath setLineWidth:0.0]; | |
[gridPath stroke]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment