http://blog.csdn.net/yixiangboy/article/details/50662704
一、案例演示
最近有一個小需求,就是要做一個圓形進度條,大概樣子如下:
。
在不知道有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];
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
我們通過以上代碼設置: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"];
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
四、聯系方式
微博:新浪微博
博客:http://blog.csdn.net/yixiangboy
github:https://github.com/yixiangboy
- 頂
- 0
