Cocoa NSView: Making circles but they are getting cropped

2.5k views Asked by At

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.

1

There are 1 answers

2
v1Axvw On BEST ANSWER

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