O'Reilly logo

Learning Cocoa by Apple Computer Inc

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Draw with NSBezierPath

In this section you’ll modify the Simple Draw application you created in Section 1.4, to draw some simple shapes in the view using NSBezierPath.

Draw Lines and Rectangles

You’ll begin your exploration of NSBezierPath by extending Simple Draw’s drawRect: method so that it will:

  • Fill the view with an opaque white background

  • Bisect the view with a pair of light gray crosshairs

  • Draw a thin black border around the view

Here’s how it works:

Open MyView.m and extend the drawRect: implementation as follows:

- (void)drawRect:(NSRect)rect
{
    NSRect myBounds = [self bounds];
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];

    // Paint a white background.
    [[NSColor whiteColor] set];
    [NSBezierPath fillRect:myBounds];

    // Draw some crosshairs on the view.
    [[NSColor lightGrayColor] set];

    [NSBezierPath strokeLineFromPoint:
            NSMakePoint(0,(myBounds.size.height/2.0))
            toPoint:NSMakePoint(myBounds.size.width, (myBounds.size.height/2.0))];

    [NSBezierPath strokeLineFromPoint:
            NSMakePoint((myBounds.size.width/2.0), 0)
            toPoint:NSMakePoint((myBounds.size.width/2.0), myBounds.size.height)];

    // Draw a black border around the view.
    [[NSColor blackColor] set];
    [NSBezierPath strokeRect:myBounds];

    // Render a string.
    [attrs setObject: font forKey: NSFontAttributeName];
    [string drawAtPoint: 
            NSMakePoint((myBounds.size.width/4.0), 5) withAttributes: attrs];
}

The new version of the drawRect: method starts by creating an NSColor object initialized to the color white and then sends it ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required