如何使用NSBezierPath绘制平滑路径

时间:2011-02-02 06:03:00

标签: cocoa nsbezierpath

我目前正在使用NSBezierPath:

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

但这条线看起来很丑陋(不顺畅)

然后我用谷歌搜索了一些解决方案,我得到了这个:

- (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];
}

但对我来说,注意到了改变,我仍然有一条丑陋的道路。

有什么建议吗?

感谢您的回答。

以下是详细信息:

  1. 创建一个cocoa应用程序(不是基于文档的)
  2. 创建一个新类“StretchView”
  3. 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.打开“界面”构建器并将“滚动视图”拖动到主窗口
    4.选择“滚动视图”并设置类“StretchView”(在类标识窗口中)

1 个答案:

答案 0 :(得分:0)

使用lineToPoint只会创建直线曲折线,即使是贝塞尔曲线路径的一部分。如果通过“平滑”表示“曲线”,那么您应该查看curveToPoint。此外,请注意这些“toPoint”方法已经移动了点,除非您打算移动到与线结束位置不同的点,否则不需要moveToPoint

相关问题