How to draw smooth path with NSBezierPath
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 solut开发者_开发技巧ions 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:
- Create a cocoa application (not document-based)
- 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)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.
精彩评论