How to draw smooth path with NSBezierPath

3.1k views Asked by At

I am draing path with NSBezierPath currently:

- (void)drawRect:(NSRect)dirtyRect 
{
    [[NSColor blueColor] set];
    [path stroke];
}

But the line seems pretty ugly(not smooth)

Then I googled for some solutions and I got this:

- (void)drawRect:(NSRect)dirtyRect 
{
    NSGraphicsContext *graphicsContext;
    BOOL oldShouldAntialias;

    graphicsContext = [NSGraphicsContext currentContext];
    oldShouldAntialias = [graphicsContext shouldAntialias];
    [graphicsContext setShouldAntialias:NO];

    [[NSColor blueColor] set];
    [path stroke];

    [graphicsContext setShouldAntialias:oldShouldAntialias];
}

But for me, noting changed, I still got the ugly path.

Any suggestion?

Thanks for answer.

Here's the details:

  1. Create a cocoa application (not document-based)
  2. Create a new class "StretchView"

StretchView.h

#import <Cocoa/Cocoa.h>

@interface StretchView : NSView {

    NSBezierPath *path;
}

-(void)myTimerAction:(NSTimer *) timer;

@end

StretchView.m

#import "StretchView.h"

@implementation StretchView

- (id)initWithFrame:(NSRect)frame 
{
    self = [super initWithFrame:frame];
    if (self) {

        path = [[NSBezierPath alloc] init]; 
        NSPoint p = CGPointMake(0, 0); 
        [path moveToPoint:p]; 
        myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                   target:self
                                                 selector:@selector(myTimerAction:)
                                                 userInfo:nil
                                                  repeats:YES];
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect 
{
    NSLog(@"drawRect");

    [[NSColor blueColor] set];
    [path stroke];
}

-(void)myTimerAction:(NSTimer *) timer
{  
    NSPoint p = CGPointMake(a, b); //a, b is random int val
    [path lineToPoint:p]; 
    [path moveToPoint:p]; 
    [path closePath];

    [self setNeedsDisplay:YES];
} 

-(void)dealloc
{
    [path release]; 
    [super dealloc];
}

@end

3.Open the Interface builder and drag a "Scroll view" to the main window
4.Choose the "Scroll view" and set the class "StretchView" (in class identity window)

1

There are 1 answers

0
EFC On

Using lineToPoint will just create straight zigzaggy lines, even as part of a bezier path. If by "smooth" you mean "curvy", then you should probably check out curveToPoint instead. Also, note that these "toPoint" methods already move the point, no need to moveToPoint unless you intend to move to a different point than where your line ended.