PDA

View Full Version : Problems getting an NSBezierPath to appear in a custom view




GorillaPaws
Jun 22, 2009, 08:31 PM
I'm trying to draw a few lines as individual NSBezierPath objects (I'm keeping them independant so that I can later do some core animation on them). I'm having issues getting the lines to appear, and I'm sure I'm missing something obvious. Here is my code for drawing my lineA:


- (id) initWithFrame: (NSRect) rect
{
if (![super initWithFrame: rect])
return nil;

NSLog (@"drawing my custom view");
NSRect bounds = [self bounds];

//make the points
NSPoint point1 = NSMakePoint ((bounds.origin.x) + 100, (bounds.origin.y) + 200);
NSPoint point2 = NSMakePoint ((bounds.origin.x) + 100, (bounds.origin.y) + 50);

//create the lines
lineA = [[NSBezierPath alloc] init];
[lineA setLineWidth: 3.0];
[[NSColor blackColor] set];
[lineA moveToPoint: point1];
[lineA lineToPoint: point2];
[lineA stroke];

[self drawRect: rect];

return self;
}


It builds fine although I'm getting CGContext errors on the console when my custom view tries to load. Also, I'm not seeing my 3pt wide vertical black line. I suspect this has something to do with the background (or lack-thereof) but any help/direction you could provide would be greatly appreciated.



kainjow
Jun 22, 2009, 08:57 PM
In an NSView you need to put your drawing code inside the drawRect: method, because this method gets called automatically by Cocoa when the view needs updating. You can tell the view to update via setNeedsDisplay:YES.

So it'd look something like:
- (void)drawRect:(NSRect)rect
{
NSLog (@"drawing my custom view");
NSRect bounds = [self bounds];

//make the points
NSPoint point1 = NSMakePoint ((bounds.origin.x) + 100, (bounds.origin.y) + 200);
NSPoint point2 = NSMakePoint ((bounds.origin.x) + 100, (bounds.origin.y) + 50);

//create the lines
lineA = [[NSBezierPath alloc] init];
[lineA setLineWidth: 3.0];
[[NSColor blackColor] set];
[lineA moveToPoint: point1];
[lineA lineToPoint: point2];
[lineA stroke];
}

GorillaPaws
Jun 22, 2009, 09:09 PM
Worked beautifully in the drawRect: method. My only problem is that these lines will be changing and if I include this code in the drawRect method then I won't be able to customize their behavior or am I missing something?

kainjow
Jun 22, 2009, 09:21 PM
If you're only drawing a few simple paths and not drawing very often, you don't need to cache the NSBezierPath objects. You can just create the paths directly each time in the drawRect: method based on whatever values you need.