Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Drawing with NSBezierPath

If you want to draw lines, ovals, curves, or polygons, you will use NSBezierPath. In this chapter, you 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 12.14).

Figure 12.14 Completed Application

The first thing you will need is an instance variable to hold on to the instance of NSBezierPath. You are also going to 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

Now in StretchView.m, you are going to override initWithFrame:. initWithFrame: is the designated initializer for views, and it will get called automatically when an instance of your view is created. In your version of initWithFrame:, you are going to 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
{
    int i;
    NSPoint p;
    
    if (self = [super initWithFrame: rect]) {
      // Seed the the random number generator
      srandom(time(NULL));

      // Create a path object
      path = [[NSBezierPath alloc] init];
      [path setLineWidth: 2.3];
      p = [self randomPoint];
      [path moveToPoint: p];
      for (i = 0; i < 15; i++) {
          p = [self randomPoint];
          [path lineToPoint: p];
      }
      [path closePath];
    }
     return self;
}

// randomPoint returns a random point inside the view
- (NSPoint)randomPoint
{
    NSPoint result;
    NSRect r;
    int width, height;
    r = [self bounds];
    width = round(r.size.width);
    height = round (r.size.height);
    result.x = (random() % width) + r.origin.x;
    result.y = (random() % height) + r.origin.y;
    return result;
}

- (void)drawRect:(NSRect)rect
{
    NSRect r = [self bounds];

    // Fill view with green
    [[NSColor greenColor] set];
    [NSBezierPath fillRect: r];

    // Draw the path in white
    [[NSColor whiteColor] set];
    [path stroke];
}

- (void)dealloc
{
    [path release];
    [super dealloc];
}
@end

Build and run your app.

  • + Share This
  • 🔖 Save To Your Account