Drawing a simple sine wave in Cocoa

Viro

Registered
I'm trying to get a hang of drawing under Cocoa. To this end, I've tried to get my own plot of a sine wave. I'm doing this my dragging a custom NSView onto my Window, and then setting the custom class to my own SineView (which inherits from NSView). Now, how do I go about plotting the line?

Here is my code.

Code:
- (void)drawRect:(NSRect)rect
{
	NSPoint origin;
	int i;
	NSRect bounds = [self bounds];
	NSBezierPath *path = [NSBezierPath bezierPath];
	
	//clear teh background
	[[NSColor whiteColor] set];
	NSRectFill(bounds);
	
	//move to middle of graph to start drawing
	origin = NSMakePoint(0,bounds.size.height/2);
	[path moveToPoint:origin];
	
	//set brush color
	[[NSColor blackColor] set];
	[NSBezierPath strokeRect:bounds];
	
	//draw sine wave
	for(i = 0; i < 360; i++) {
		//calculate next position
		origin.y = sin(i/360 * 3.142) * bounds.size.height/10;
		origin.x = i;
		[path lineToPoint:origin];
	}
}

It clears the background correctly. It also draws the strokeRect correctly (I get an outline of the View. But for some reason it refuses to draw my sine wave. What am I doing wrong?
 
I think you have forgotten to include the following after the for loop:

[path stroke];

The stroke method acts like a pen tracing the path, making it visible.
 
Back
Top