在可可画线?

时间:2012-04-28 00:05:41

标签: objective-c macos drawing nsbezierpath

单击按钮后如何在特定窗口中绘制线条?

我正在使用这个:

NSBezierPath * path = [NSBezierPath bezierPath];
        [path setLineWidth: 4];

        NSPoint startPoint = {  21, 21 };
        NSPoint endPoint   = { 128,128 };
        [path  moveToPoint: startPoint];    
        [path lineToPoint:endPoint];

        [[NSColor redColor] set]; 
        [path stroke];

但只有当我把它放在:

时它才有用
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification

我怎么能解决这个问题? 我的目标是创建一个可以根据收到的细节(坐标)绘制线条的应用程序

谢谢。

3 个答案:

答案 0 :(得分:2)

您不应该在视图或图层的绘图方法之外绘图(例如drawRect:)。你想要做的是,在广泛的笔触中,有一个视图,在设置标志时绘制线条,当你点击按钮时,设置标志并告诉视图重绘。

答案 1 :(得分:2)

单击鼠标事件时。此代码将创建直线,曲线和绘图。

  #import <Cocoa/Cocoa.h>


    @interface BezierView : NSView {
        NSPoint points[4];
        NSUInteger pointCount;
    }

    @end

    #import "BezierView.h"

    @implementation BezierView
    - (id)initWithFrame:(NSRect)frame {
        self = [super initWithFrame:frame];
        if (self) {
            // Initialization code here.
        }
        return self;
    }

    - (void)drawRect:(NSRect)rect 
    {
        NSBezierPath *control1 = [NSBezierPath bezierPath];
        [control1 moveToPoint: points[0]];
        [control1 lineToPoint: points[1]];
        [[NSColor redColor] setStroke];
        [control1 setLineWidth: 2];
        [control1 stroke];

        NSBezierPath *control2 = [NSBezierPath bezierPath];
        [control2 moveToPoint: points[2]];
        [control2 lineToPoint: points[3]];
        [[NSColor greenColor] setStroke];
        [control2 setLineWidth: 2];
        [control2 stroke];

        NSBezierPath *curve = [NSBezierPath bezierPath];
        [curve moveToPoint: points[0]];
        [curve curveToPoint: points[3]
              controlPoint1: points[1]
              controlPoint2: points[2]];

        [[NSColor blackColor] setStroke];
        CGFloat pattern[] = {4, 2, 1, 2};
        [curve setLineDash: pattern
                     count: 4
                     phase: 1];
        [[NSColor grayColor] setFill];
        [curve fill];
        [curve stroke];
    }

    - (void)mouseDown: (NSEvent*)theEvent
    {
        NSPoint click = [self convertPoint: [theEvent locationInWindow]
                                  fromView: nil];
        points[pointCount++ % 4] = click;
        if (pointCount % 4 == 0)
        {
            [self setNeedsDisplay: YES];
        }
    }
    @end

答案 2 :(得分:0)

您是否尝试在完成绘图时调用[yourView setNeedsDisplay:YES]?