2

the outer edges of my circle at each point of the compass are getting cropped (presumably by the rect frame). How do I get the circle to display within the frame? (This is getting created from a button click):

In my AppController.m

#import "AppController.h"
#import "MakeCircle.h"

@implementation AppController

- (IBAction)makeCircle:(id)sender {

     MakeCircle* newCircle = [[MakeCircle alloc] initWithFrame:NSMakeRect(100.0, 100.0, 30.0, 30.0)];
     [[[[NSApplication sharedApplication] mainWindow] contentView] addSubview:newCircle];

     [newCircle release];
}

@end

In my MakeCircle.m

- (void)drawRect:(NSRect)rect {

     [self setNeedsDisplay:YES];

     [[NSColor blackColor] setStroke];

     // Create our circle path
     NSBezierPath* circlePath = [NSBezierPath bezierPath];
     [circlePath appendBezierPathWithOvalInRect: rect];

     //give the line some thickness
     [circlePath setLineWidth:4];

     // Outline and fill the path
     [circlePath stroke];


  }

Thanks.

PruitIgoe
  • 6,166
  • 16
  • 70
  • 137

1 Answers1

6

I think you see only half of the edge, right? You can calculate the half of the thickness of the edge and subtract that from the rectangle:

#define STROKE_COLOR    ([NSColor blackColor])
#define STROKE_WIDTH    (4.0)
- (void)drawRect:(NSRect)dirtyRect {
    NSBezierPath *path;
    NSRect rectangle;

    /* Calculate rectangle */
    rectangle = [self bounds];
    rectangle.origin.x += STROKE_WIDTH / 2.0;
    rectangle.origin.y += STROKE_WIDTH / 2.0;
    rectangle.size.width -= STROKE_WIDTH / 2.0;
    rectangle.size.height -= STROKE_WIDTH / 2.0;
    path = [NSBezierPath path];
    [path appendBezierPathWithOvalInRect:rectangle];
    [path setLineWidth:STROKE_WIDTH];
    [STROKE_COLOR setStroke];
    [path stroke];
}

I have no Mac at the moment, so I can't test it, but I think it should solve your problem.

Als don't call [self setNeedsDisplay:YES]. The method is used when you want to redraw your whole NSView, and calling it from the drawing method is a little bit recursive. That's why I'm surprised your code actually draws something.

And I have another tip: [[NSApplication sharedApplication] mainWindow] is actually the same as [NSApp mainWindow]. NSApp is a global variable containing the main application.

Hope it helps,
ief2

v1Axvw
  • 3,054
  • 3
  • 26
  • 40
  • thanks, I kind of figured out the same thing - there's no method/property to tell cocoa where to draw the stroke similar to what you can do in Photoshop - stroke inside, center, outside? - and thanks for the NSApp tip... – PruitIgoe Feb 09 '11 at 16:09
  • 1
    I changed these two lines from: rectangle.size.width -= STROKE_WIDTH/2; rectangle.size.height -= STROKE_WIDTH/2; to rectangle.size.width -= STROKE_WIDTH; rectangle.size.height -= STROKE_WIDTH; – PruitIgoe Feb 09 '11 at 18:31