3

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

我正在使用这个:

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

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

谢谢你。

4

2 回答 2

2

您不应该在视图或图层的绘制方法之外进行绘制(例如drawRect:)。概括地说,您想要做的是有一个视图,在设置标志时绘制线,当您单击按钮时,设置标志并告诉视图重绘。

于 2012-04-28T00:52:41.537 回答
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
于 2015-09-15T09:22:01.400 回答