使用CAShapeLayer做一個(gè)高性能的畫板(OC版)

Swift版原文

touchesBegan方法中初始化一個(gè)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;
    // 終點(diǎn)處理
    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;
    }
    }
運(yùn)行效果:

![畫板.gif](http://upload-images.jianshu.io/upload_images/2666834-bbc6a861b2674bb4.gif?imageMogr2/auto-orient/strip)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,180評(píng)論 4 61
  • 我伸手去觸碰你 穿過(guò)二百二十七公里的距離 如同一只攀爬的蛇 我細(xì)長(zhǎng)的胳膊 在手指的帶領(lǐng)下 無(wú)盡的延長(zhǎng) 他們翻過(guò)霧氣...
    李小陪閱讀 253評(píng)論 2 2
  • 本文講述第八章的內(nèi)容。 本章的主題是從過(guò)去的自己走到未來(lái)的自己。 從過(guò)去一路走來(lái),磕磕碰碰,也許經(jīng)歷太多,有時(shí)候不...
    kidII閱讀 304評(píng)論 0 0
  • 以前瘋狂的愛(ài)著一個(gè)胖子 后來(lái),胖子變成了瘦子 而我,做了信使 傳遞著憂傷的故事 后來(lái),故事被我寫成了詩(shī) 留在一個(gè)叫...
    周門近安閱讀 288評(píng)論 1 6
  • 楓葉飄過(guò) 幸福依然記得水府的夢(mèng) 問(wèn)一問(wèn)昨夜的淚 只是晚霞染紅楓葉飄過(guò)的醉 夢(mèng)想的天空總是下著雨 那或許就是楓葉飄過(guò)...
    米瀾盛若閱讀 174評(píng)論 1 3