在NSView上绘制线条

时间:2018-02-02 19:53:34

标签: objective-c macos cocoa nsview

我试图在NSView上绘制连接15个随机点的行,但是我没有看到任何行。 StretchView.h:

 #import <Cocoa/Cocoa.h>

@interface StretchView : NSView {
    NSBezierPath *myPath;
}

-(NSPoint)randomPoint;

@end

StretchView.m:

    #import "StretchView.h"

@implementation StretchView

-(id)initWithFrame:(NSRect)frame{

    self=[super initWithFrame:frame];
    if(self){
        srandom(time(NULL));
        myPath=[[NSBezierPath alloc]init];
        [myPath setLineWidth:1.5]; //width of the lines
        NSPoint aPoint= [self randomPoint];
        [myPath moveToPoint:aPoint];
        for(int i=0; i<15; i++){
            aPoint=[self randomPoint]; //call the function randomPoint defined below 

            [myPath lineToPoint:aPoint]; //join the following point

        }

        [myPath closePath];  

    }
    return self;
}

随机点的定义,它提供了一个带有从x原点坐标到宽度大小的随机x场的点。并且从y原点坐标到高度大小的y字段:

-(NSPoint)randomPoint
{
    NSPoint result;
    NSRect r= [self bounds];
    result.x=r.origin.x+random()%(int)r.size.width;
    result.y=r.origin.y+random()%(int)r.size.height;
    return result;
}

drawRect的功能

- (void)drawRect:(NSRect)dirtyRect {

        NSRect bounds=[self bounds];
        [[NSColor greenColor]set];
        [NSBezierPath fillRect:bounds];
        [[NSColor whiteColor]setStroke];
        [myPath stroke];

    }

    @end

0 个答案:

没有答案