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

2016-08-17  本文已影响0人  我是一个TableView

Swift版原文

touchesBegan方法中初始化一个CAShapeLayer:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    CGPoint point = [self pointWithTouches:touches];
    if (event.allTouches.count == 1) {
        [self initStartPath:point];
    }
}
- (CGPoint)pointWithTouches:(NSSet<UITouch *> *)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```方法中更新贝塞尔曲线的路径
运行效果:

![画板.gif](https://img.haomeiwen.com/i2666834/bbc6a861b2674bb4.gif?imageMogr2/auto-orient/strip)
上一篇 下一篇

猜你喜欢

热点阅读