【问题标题】:How to draw smooth path with NSBezierPath如何使用 NSBezierPath 绘制平滑路径
【发布时间】:2023-03-21 23:41:01
【问题描述】:

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

【问题讨论】:

  • 请附上截图说明问题。
  • 另外,请告诉我们这个drawRect方法的位置(它只是一个简单的视图,还是类似NSTableView的东西?)以及设置路径的代码。
  • 您可能希望打开,而不是关闭...

标签: cocoa nsbezierpath


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-11-28
    • 2011-10-01
    • 1970-01-01
    • 2015-04-29
    • 2013-12-12
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多