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

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](http://upload-images.jianshu.io/upload_images/2666834-bbc6a861b2674bb4.gif?imageMogr2/auto-orient/strip)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,267评论 4 61
  • 我伸手去触碰你 穿过二百二十七公里的距离 如同一只攀爬的蛇 我细长的胳膊 在手指的带领下 无尽的延长 他们翻过雾气...
    李小陪阅读 266评论 2 2
  • 本文讲述第八章的内容。 本章的主题是从过去的自己走到未来的自己。 从过去一路走来,磕磕碰碰,也许经历太多,有时候不...
    kidII阅读 310评论 0 0
  • 以前疯狂的爱着一个胖子 后来,胖子变成了瘦子 而我,做了信使 传递着忧伤的故事 后来,故事被我写成了诗 留在一个叫...
    周门近安阅读 291评论 1 6
  • 枫叶飘过 幸福依然记得水府的梦 问一问昨夜的泪 只是晚霞染红枫叶飘过的醉 梦想的天空总是下着雨 那或许就是枫叶飘过...
    米澜盛若阅读 180评论 1 3