iOS開發基礎篇--CAShapeLayer的strokeStart和strokeEnd屬性

邏輯教育-楚陽發表於2018-11-27

一、案例演示

最近有一個小需求,就是要做一個圓形進度條,大概樣子如下:

iOS開發基礎篇--CAShapeLayer的strokeStart和strokeEnd屬性

1.gif。

在不知道有CAShapeLayer的strokeStart和strokeEnd屬性的時候,我採取的方法就是實時的 移除舊的CAShapeLayer 然後重繪這個圓形的CAShapeLayer。顯然這種方式的效率是不高的。後來在一次看別人Demo的時候,發現別人使用了CAShapeLayer的strokeStart和strokeEnd屬性,實現這一個效果十分的簡單方便。下面就和大家來講一講這兩個屬性的使用。

二、屬性詳解

蘋果官方給出這兩個屬性的解釋為:

  • These values define the subregion of the path used to draw the
  • stroked outline. The values must be in the range [0,1] with zero
  • representing the start of the path and one the end. Values in
  • between zero and one are interpolated linearly along the path
  • length. strokeStart defaults to zero and strokeEnd to one. Both are
  • animatable. */

大概意思就是:我們可以對繪製的Path進行分割槽。這兩個屬性的值在0~1之間,0代表Path的開始位置,1代表Path的結束位置。是一種線性遞增關係。strokeStart預設值為0,strokeEnd預設值為1。這兩個屬性都支援動畫。

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.frame = _demoView.bounds;
    shapeLayer.strokeEnd = 0.7f;
    shapeLayer.strokeStart = 0.1f;

    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:_demoView.bounds];

    shapeLayer.path = path.CGPath;

    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.lineWidth = 2.0f;
    shapeLayer.strokeColor = [UIColor redColor].CGColor;

    [_demoView.layer addSublayer:shapeLayer];
複製程式碼

我們通過以上程式碼設定:strokeStart=0.1f; strokeEnd=0.7f則顯示如下圖所示。

三、圓形進度條實現程式碼

綜上所述我們知道,strokeStart和strokeEnd可以設定一條Path的起始和終止的位置,通過利用strokeStart和strokeEnd這兩個屬性支援動畫的特點,我們通過以下程式碼就可以實現圓形進度條的效果。

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.frame = _demoView.bounds;

    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:_demoView.bounds];

    shapeLayer.path = path.CGPath;

    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.lineWidth = 2.0f;
    shapeLayer.strokeColor = [UIColor redColor].CGColor;

    [_demoView.layer addSublayer:shapeLayer];

    CABasicAnimation *pathAnima = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnima.duration = 3.0f;
    pathAnima.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    pathAnima.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnima.toValue = [NSNumber numberWithFloat:1.0f];
    pathAnima.fillMode = kCAFillModeForwards;
    pathAnima.removedOnCompletion = NO;
    [shapeLayer addAnimation:pathAnima forKey:@"strokeEndAnimation"];
複製程式碼

四、最後說一點

這是一個我的iOS交流群:624212887,群檔案自行下載,不管你是小白還是大牛熱烈歡迎進群 ,分享面試經驗,討論技術, 大家一起交流學習成長!希望幫助開發者少走彎路。——點選:加入

如果覺得對你還有些用,就關注小編+喜歡這一篇文章。你的支援是我繼續的動力。

下篇文章預告:UITableview巢狀UITableView案例實踐(仿淘寶商品詳情頁實現)

文章來源於網路,如有侵權,請聯絡小編刪除。


相關文章