美文网首页
使用CAShapeLayer做一个高性能的画板(OC版)

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

作者: 我是一个TableView | 来源:发表于2016-08-17 12:05 被阅读0次

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```方法中更新贝塞尔曲线的路径
  • (void)touchesMoved:(NSSet<UITouch *> *)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](https://img.haomeiwen.com/i2666834/bbc6a861b2674bb4.gif?imageMogr2/auto-orient/strip)

相关文章

网友评论

      本文标题:使用CAShapeLayer做一个高性能的画板(OC版)

      本文链接:https://www.haomeiwen.com/subject/plqjsttx.html