标签:
最近有一个小需求,就是要做一个圆形进度条,大概样子如下:
。
在不知道有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"];
微博:新浪微博
博客:http://blog.csdn.net/yixiangboy
github:https://github.com/yixiangboy
IOS开发基础篇--CAShapeLayer的strokeStart和strokeEnd属性
标签:
原文地址:http://www.cnblogs.com/itlover2013/p/5189811.html