user7056422
user7056422

Reputation:

Why my NSBezierPath is not showing?

So i recieve a notification with the data i need to draw my path. This code is from my main app controller:

-(void) handleAdd:(NSNotification *)aNotification{
NSLog(@"x1:%f y1:%f x2:%f y2:%f ",[panelController x1],[panelController y1],[panelController x2],[panelController y2]);

myPath = [[NSBezierPath alloc]init];
[myPath setLineWidth:[panelController grosor]];

[myPath moveToPoint:NSMakePoint([panelController x1],[panelController y1])];
[myPath lineToPoint:NSMakePoint([panelController x2],[panelController y2])];
[[panelController trazado] setStroke];
[myPath stroke];
}

The NSLog is showing me the right data. I have a view created and in that white rectangle is where i want to draw.

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
        }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
    NSRect bounds= [self bounds];
    [[NSColor whiteColor] set];
    [NSBezierPath fillRect:bounds];
}

If i draw in that class the stroke is showing, but how could i draw on that view from the controller? Or should i just receive the notification in the view and draw from that class?

Upvotes: 1

Views: 313

Answers (1)

Warren Burton
Warren Burton

Reputation: 17382

You can't (easily) draw from the controller into the view.

Think of your views drawRect method as a complete set of instructions of what to draw at every refresh.

So right now all you are saying is "fill me with white"

You need to handle all the relevant drawing within the views drawRect: method.

Adjust your controller method to this.

-(void) handleAdd:(NSNotification *)aNotification{
    [myViewInstance setNeedsDisplay:YES]; //also myViewInstance.needsDisplay = YES
}

And assuming the view has a reference to the panel controller…

@interface MyView: UIView 

//weak as you don't want a reference cycle
@property (weak) MyPanelController *panelController;

@end

@implementation MyView

- (void)drawRect:(NSRect)dirtyRect
{
    NSRect bounds= [self bounds];
    [[NSColor whiteColor] set];
    [NSBezierPath fillRect:bounds];

    NSBezierPath *myPath = [[NSBezierPath alloc]init];
    [myPath setLineWidth:[self.panelController grosor]];

    [myPath moveToPoint:NSMakePoint([self.panelController x1],[self.panelController y1])];
    [myPath lineToPoint:NSMakePoint([self.panelController x2],[self.panelController y2])];
    [[self.panelController trazado] setStroke];
    [myPath stroke];
}

@end

If you want explore your first technique you want to look at at NSView and the lockFocus/unlockFocus methods. The documentation explains why you probably don't want to do this.

Upvotes: 3

Related Questions