cocoa - 使用 NSBezierPath 时切换线条属性

标签 cocoa graphics

使用 NSBezierPath 绘制不同的线条(用于图表)时,我在更改线条颜色/宽度时遇到了一些非常基本的问题。下面的代码应该清楚地表明我想要做什么:

#import "DrawTest.h"

@implementation DrawTest

- (id)initWithFrame:(NSRect)frameRect
{
NSLog(@"in 'initWithFrame'...");
    if ((self = [super initWithFrame:frameRect]) != nil)
        {
    [self drawBaseline];
    [self display]; // ...NO!
    [self drawPlotline];
    }
return self;
}

- (void)drawBaseline
{
    NSRect windowRect;
    int width, height;

    windowRect = [self bounds];
    width = round(windowRect.size.width);
    height = round(windowRect.size.height);

    theLineWidth=1.0;
    [[NSColor grayColor] set];
    // allocate an instance of 'NSBezierPath'...
    path = [[NSBezierPath alloc]init];
    // draw a HORIZONTAL line...
    [path moveToPoint:NSMakePoint(0,height/2)];
    [path lineToPoint:NSMakePoint(width,height/2)];
}

- (void)drawPlotline
{
    theLineWidth=10.0;
    [[NSColor redColor] set];
    // draw a VERTICAL line...
    [path moveToPoint:NSMakePoint(100,125)]; // x,y
    [path lineToPoint:NSMakePoint(100,500)];
}

- (void)drawRect:(NSRect)rect
{
NSLog(@"in 'drawRect'...");
    // draw the path line(s)
    //  [[NSColor redColor] set];
    [path setLineWidth:theLineWidth];
    [path stroke];
}

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

@end

问题显然在于“drawRect”仅被调用一次(在两种方法都运行之后),结果是所有线条都出现在最后设置的颜色和线条宽度中。我尝试过调用 [self display] 等,希望强制“drawRect”在两个方法调用之间重绘 NSView 内容,但无济于事。

任何人都可以建议一个基本策略来实现我在这里想做的事情吗?任何帮助将不胜感激。

最佳答案

快速答案是:将[self drawBaseline][self drawPlotline]移动到drawRect内。 此外,在更改颜色之前,您需要为每种颜色调用一次[path Stroke]。所以,伪代码是这样的

-(void)drawRect:(NSRect)rect
{
      NSBezierPath*path1=...
      construct the path for color red...
      [[NSColor redColor] set];
      [path1 stroke]; 

      NSBezierPath*path2=...
      construct the path for color blue...
      [[NSColor blueColor] set];
      [path2 stroke]; 

}

记住:

  • [path moveToPoint:] 等不会绘制路径。它只是构造对象内部的路径。构建完成后,您可以使用[路径描边]描边路径。

  • 此外,颜色不是 NSBezierPath 实例内构造的路径的属性。因此,[color set] 未记录在您的 NSBezierPath 实例中!它是图形上下文的属性。从概念上讲,1. 您构建路径。 2. 将颜色设置为上下文。 3. 你抚摸路径。

  • 在 Cocoa 中,并不是您告诉系统何时绘制、何时刷新等。Cocoa 告诉您何时绘制,通过调用 drawRect:.您绘制的图形上下文在 drawRect: 之外不可用,除非您自己创建离屏上下文。所以,不用费心事先画图。只需在 drawRect 中绘制所有内容即可。

关于cocoa - 使用 NSBezierPath 时切换线条属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2188277/

相关文章:

android - 为 Android WebView 启用 WebGL 支持

iphone - 使用 Core Data 实现枚举的最佳方法

objective-c - LDAP 身份验证,ldap_sasl_bind_s 不工作但 ldap_simple_bind_s 工作

objective-c - 计算下一个生日日期

c++ - OpenGL 阴影贴图 - 阴影贴图纹理根本没有被采样?

C# Windows 窗体控件到图像?

java - 平滑快速移动和重绘()

cocoa - 最后一个窗口关闭后退出应用程序

objective-c - 将 NSSlider 与 NSTableView 绑定(bind)

java - 类似 Agar.io 的细胞物理学