UIBezierPath+CAShapeLayer绘制进度环
2017-10-24 本文已影响44人
makemake
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self masLayoutSubview];
}
return self;
}
+ (instancetype)bezierPathWithArcCenter:(CGPoint)center radius:(CGFloat)radius startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle clockwise:(BOOL)clockwise;
:(CGPoint)center
中心点
:(CGFloat)radius
半径
:(CGFloat)startAngle
起点
:(CGFloat)endAngle
终点
:(BOOL)clockwise
是否顺时针
- (void)masLayoutSubview{
bottomPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0) radius:self.frame.size.width/2.0 - 10 startAngle:- M_PI_2 endAngle:-M_PI_2 + M_PI * 2 clockwise:YES];
CAShapeLayer *bottomLayer = [CAShapeLayer layer];
bottomLayer.frame = self.bounds;
bottomLayer.path = bottomPath.CGPath;
bottomLayer.lineWidth = lineWidth;
bottomLayer.strokeColor = [UIColor grayColor].CGColor;
bottomLayer.fillColor = nil;
[self.layer addSublayer:bottomLayer];
layer = [CAShapeLayer layer];
layer.frame = self.bounds;
layer.lineWidth = lineWidth;
layer.fillColor = nil;
layer.lineCap = kCALineCapRound;
self.layer.contentsScale = [[UIScreen mainScreen]scale];
[self.layer addSublayer:layer];
}
对外提供设置进度接口:(不用多次addsubLayer,直接修改CAShapeLayer的path路径就可以了)
CABasicAnimation 看情况是否加
- (void)setProgress:(CGFloat)value{
path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0) radius:self.frame.size.width/2.0 - 10
startAngle:3*M_PI_2 endAngle:3*M_PI_2+(2*M_PI*value) clockwise:YES];
layer.path = path.CGPath;
// CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
// animation.fromValue = @(0.0);
// animation.toValue = @(1.0);
// animation.duration = 1.f;
// [layer addAnimation:animation forKey:nil];
}
效果如下:
picture.gif难点:
定义圆环的起点为3/2π
也就是3*M_PI_2
,计算终点的公式为3*M_PI_2+(2*M_PI*value)