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 回答
0

这是为我工作的代码,我传递了 lineWidth 参数:

画线.h 文件

#import <Cocoa/Cocoa.h>

@interface DrawLine : NSView
@property (nonatomic, strong) double *lineWidth;
@property (nonatomic, strong) UIColor *color;
- (void)drawRect:(CGRect)rect;
- (id)initWithFrame:(NSRect)frameRect andLineWidth :(double)lineWidth0 andColor: (UIColor *) color0;
...
@end

画线.m 文件

...
- (id)initWithFrame:(NSRect)frameRect andLineWidth :(double)lineWidth0 andColor: (UIColor *) color0;
{
    self.lineWidth = lineWidth0;
    self = [super initWithFrame:frameRect];
if (self) {
    // Initialization code
    [super setBackgroundColor:color0];
}
return self;
    return self;
}
...

ViewController.m 文件

...
- (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;

    double lineWidth = 10;
    UIColor *color = [UIColor clearColor];

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

有用。

于 2015-04-16T00:58:46.930 回答