使用CAShapeLayer做一个高性能的画板(OC版)

Swift版原文

touchesBegan方法中初始化一个CAShapeLayer:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    CGPoint point = [self pointWithTouches:touches];
    if (event.allTouches.count == 1) {
        [self initStartPath:point];
    }
}
- (CGPoint)pointWithTouches:(NSSet *)touches{
    UITouch *touch = (UITouch *)touches.anyObject;
    return [touch locationInView:self.view];
}

初始化CAShapeLayer:

- (void)initStartPath:(CGPoint)startPoint{
    UIBezierPath *path = [[UIBezierPath alloc] init];
    path.lineWidth = 2;
    // 线条拐角
    path.lineCapStyle = kCGLineCapRound;
    // 终点处理
    path.lineJoinStyle = kCGLineJoinRound;
    [path moveToPoint:startPoint];
    self.lastPath = path;
    
    CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init];
    shapeLayer.path = path.CGPath;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.lineCap = kCALineCapRound;
    shapeLayer.lineJoin = kCALineJoinRound;
    shapeLayer.strokeColor = [UIColor redColor].CGColor;
    shapeLayer.lineWidth = path.lineWidth;
    self.lastLayer = shapeLayer;
    [self.view.layer addSublayer:shapeLayer];
}```
在```touchesMoved```方法中更新贝塞尔曲线的路径
  • (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    CGPoint point = [self pointWithTouches:touches];
    if (event.allTouches.count == 1) {
    [self.lastPath addLineToPoint:point];
    self.lastLayer.path = self.lastPath.CGPath;
    }
    }
运行效果:

![画板.gif](http://upload-images.jianshu.io/upload_images/2666834-bbc6a861b2674bb4.gif?imageMogr2/auto-orient/strip)

你可能感兴趣的:(使用CAShapeLayer做一个高性能的画板(OC版))