首页 » iOS编程(第4版) » iOS编程(第4版)全文在线阅读

《iOS编程(第4版)》12.3 实现BNRDrawView,完成绘图功能

关灯直达底部

BNRDrawView对象需要管理正在绘制的线条和绘制完成的线条。在BNRDrawView.m中,先导入BNRLine.h;然后在类扩展中添加两个属性,用于保存这两种线条;最后实现initWithFrame:,代码如下:

#import “BNRDrawView.h”

#import “BNRLine.h”

@interface BNRDrawView ()

@property (nonatomic, strong) BNRLine *currentLine;

@property (nonatomic, strong) NSMutableArray *finishedLines;

@end

@implementation BNRDrawView

- (instancetype)initWithFrame:(CGRect)r

{

self = [super initWithFrame:r];

if (self) {

self.finishedLines = [[NSMutableArray alloc] init];

self.backgroundColor = [UIColor grayColor];

}

return self;

}

为了测试创建线条的代码是否正确,需要在BNRDrawView中编写绘制线条的代码。在BNRDrawView.m中实现drawRect:方法,代码如下:

- (void)strokeLine:(BNRLine *)line

{

UIBezierPath *bp = [UIBezierPath bezierPath];

bp.lineWidth = 10;

bp.lineCapStyle = kCGLineCapRound;

[bp moveToPoint:line.begin];

[bp addLineToPoint:line.end];

[bp stroke];

}

- (void)drawRect:(CGRect)rect

{

// 用黑色绘制已经完成的线条

[[UIColor blackColor] set];

for (BNRLine *line in self.finishedLines) {

[self strokeLine:line];

}

if (self.currentLine) {

// 用红色绘制正在画的线条

[[UIColor redColor] set];

[self strokeLine:self.currentLine];

}

}