2

私のViewControllerにはボタンがあります:

- (IBAction)drawLineClick:(id)sender 
{
    CGRect rect;
    rect.origin.x = 20.0f;
    rect.origin.y = 40.0f;
    rect.size.width = 100.0f;
    rect.size.height = 100.0f;

    //draw line
    DrawLine *drawLine = [[DrawLine alloc] initWithFrame:rect]; 
    [self.view addSubview:drawLine];
}

私の DrawLine クラスでは、線を引くだけです:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [super setBackgroundColor:[UIColor clearColor]];
    }
    return self;
}

- (void)drawRect:(CGRect)rect
{
    // Drawing code

    [self drawLine];
}

- (void)drawLine
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
    CGContextSetLineWidth(context, 3.0);
    CGContextMoveToPoint(context, 0, 0); 
    CGContextAddLineToPoint(context, 50, 50); 
    CGContextStrokePath(context);
}

これはうまく機能しますが、これは可変ではありません。毎回同じラインです。異なる線を描画できるように、ViewController から DrawLine クラスに線の色、線の幅などを渡すにはどうすればよいですか?

ありがとう。

4

2 に答える 2

1

制御したいものを表すプロパティを DrawLine クラスに作成します。新しいオブジェクトを作成するときは、プロパティを直接割り当てるか、カスタムinitWith...メソッドで渡すことによって、そのプロパティを設定します。drawRect: のプロパティ値を使用します。

于 2012-04-13T15:17:35.537 に答える