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 ...

Get Learning Cocoa now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.