如何用UIBezierPath画线

来源:互联网 发布:在淘宝买药可靠吗 编辑:程序博客网 时间:2024/04/27 22:34

本文讲述如何在UIView的子类中使用UIBezierPath来画图, 一般的使用方法都是在- (void)drawRect:(CGRect)rect的上下文中来画图. 现在我们来讲一讲如何不用指定上下文,在UIView中使用UIBezierPath.

一. 在子类中重写类方法+layerClass, 指定创建的图层为类CAShapeLayer 

// OTDrawView.m+ (Class)layerClass {        return[CAShapeLayer class];}
 

二. 初始化

创建一个数组存储每次按下时点的位置, 设置背景为白色, 并声明我们不使用填充及指定画线的颜色.

- (id)initWithFrame:(CGRect)frame{    self = [super initWithFrame:frame];    if (self) {       //Initialization code             points = [[NSMutableArray alloc] init];                         self.backgroundColor = [UIColor whiteColor];             ((CAShapeLayer *)self.layer).fillColor = nil;             ((CAShapeLayer *)self.layer).strokeColor = [UIColor blackColor].CGColor;    }    return self;}

三. 更新路径函数, 使用UIBezierPath根据记录的points数组, 按顺序将每条线描绘出来. 最重要的地方是把UIBezierPath的值赋给((CAShapeLayer *)self.layer).path

- (void)updatePaths{       if ([points count] >= 2) {                   UIBezierPath *path = [[UIBezierPath alloc] init];       [path moveToPoint:[[points firstObject] CGPointValue]];                   NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, [points count] - 1)];       [points enumerateObjectsAtIndexes:indexSet                                                      options:0                                                 usingBlock:^(NSValue *pointValue, NSUInteger idx, BOOL *stop) {                                                       [path addLineToPoint:[pointValue CGPointValue]];                                                 }];             ((CAShapeLayer *)self.layer).path = path.CGPath;       }       else       {             ((CAShapeLayer *)self.layer).path = nil;       }}

四. 这是我们每个点生成的地方, 每按下一次屏幕, 就会把当前点存入points数组中, 再调用updatePaths更新路径.

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{    UITouch *touch =[touches anyObject];    CGPoint point = [touch locationInView:self];    [points addObject:[NSValue valueWithCGPoint:point]];          [self updatePaths];}

 

1 0