Drawing with NSBezierPath
If you want to draw lines, ovals, curves, or polygons, you can use NSBezierPath. In this chapter, you have already used the NSBezierPath's fillRect: class method to color your view. In this section, you will use NSBezierPath to draw lines connecting random points (Figure 17.11).
Figure 17.11 Completed Application
The first thing you will need is an instance variable to hold the instance of NSBezierPath. You will also create an instance method that returns a random point in the view. Open StretchView.h and make it look like this:
#import <Cocoa/Cocoa.h> @interface StretchView : NSView { NSBezierPath *path; } - (NSPoint)randomPoint; @end
In StretchView.m, you will override initWithFrame:. As the designated initializer for NSView, initWithFrame: will be called automatically when an instance of your view is created. In your version of initWithFrame:, you will create the path object and fill it with lines to random points. Make StretchView.m look like this:
#import "StretchView.h" @implementation StretchView - (id)initWithFrame:(NSRect)rect { if (![super initWithFrame:rect]) return nil; // Seed the random number generator srandom(time(NULL)); // Create a path object path = [[NSBezierPath alloc] init]; [path setLineWidth:3.0]; NSPoint p = [self randomPoint]; [path moveToPoint:p]; int i; for (i = 0; i < 15; i++) { p = [self randomPoint]; [path lineToPoint:p]; } [path closePath]; return self; } - (void)dealloc { [path release]; [super dealloc]; } // randomPoint returns a random point inside the view - (NSPoint)randomPoint { NSPoint result; NSRect r = [self bounds]; result.x = r.origin.x + random() % (int)r.size.width; result.y = r.origin.y + random() % (int)r.size.height; return result; } - (void)drawRect:(NSRect)rect { NSRect bounds = [self bounds]; // Fill the view with green [[NSColor greenColor] set]; [NSBezierPath fillRect: bounds]; // Draw the path in white [[NSColor whiteColor] set]; [path stroke]; } @end
Build and run your app. Pretty, eh?
Okay, now try replacing [path stroke] with [path fill]. Build and run it.