Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

GorillaPaws

macrumors 6502a
Original poster
Oct 26, 2003
932
8
Richmond, VA
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:

Code:
- (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

Moderator emeritus
Jun 15, 2000
7,958
7
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:
Code:
- (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

macrumors 6502a
Original poster
Oct 26, 2003
932
8
Richmond, VA
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

Moderator emeritus
Jun 15, 2000
7,958
7
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.