使用UIBezierPath和CAShapeLayer自定义圆形
2017-11-29 本文已影响278人
诠释残缺
直线的进度条并不能满足日常的开发需求,所以我们使用UIBezierPath和CAShapeLayer来自定义
一、需要用到的知识
1.UIBezierPath
贝塞尔曲线,可以画出我们想要的许多图形。
2.CAShapeLayer
CALayer的子类,配合贝塞尔曲线实现我们的自定义控件。
UIBezierPath和CAShapeLayer的详细介绍,网上有很多。
二、自定义进度视图
1.扇形进度
_startAngle = - M_PI_2;
_endAngle = _startAngle + _progress * M_PI * 2;
UIBezierPath *fillPath = [UIBezierPath bezierPathWithArcCenter:_origin radius:_radius startAngle:_startAngle endAngle:_endAngle clockwise:YES];
[fillPath addLineToPoint:_origin];
_fillLayer.path = fillPath.CGPath;
_fillLayer.fillColor = _fillColor.CGColor;
2.球形进度
_startAngle = M_PI_2 - _progress * M_PI;
_endAngle = M_PI_2 + _progress * M_PI;
UIBezierPath *fillPath = [UIBezierPath bezierPathWithArcCenter:_origin radius:_radius startAngle:_startAngle endAngle:_endAngle clockwise:YES];
_fillLayer.path = fillPath.CGPath;
3.圆弧进度
_startAngle = - M_PI_2;
_endAngle = _startAngle + _progress * M_PI * 2;
UIBezierPath *topPath = [UIBezierPath bezierPathWithArcCenter:_origin radius:_radius - _topWidth startAngle:_startAngle endAngle:_endAngle clockwise:YES];
_topLayer.path = topPath.CGPath;
4.波浪进度
CGFloat y = _waveY;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0, y)];
for (CGFloat x = 0.0; x <= _waveWidth; x++) {
y = _waveA * sin(_waveP * x + _waveX + 0.5) + _waveY;
[path addLineToPoint:CGPointMake(x, y)];
}
[path addLineToPoint:CGPointMake(_waveWidth, self.bounds.size.height)];
[path addLineToPoint:CGPointMake(0, self.bounds.size.height)];
[path closePath];
_waveLayer.path = path.CGPath;
5.渐变色进度
//渐变层的创建
CALayer *gradientLayer = [CALayer layer];
CAGradientLayer *leftGradient = [CAGradientLayer layer];
leftGradient.frame = CGRectMake(-layerWidth/2, -layerWidth/2, self.bounds.size.width / 2 + layerWidth/2, self.bounds.size.height + layerWidth);
leftGradient.colors = @[(id)[UIColor yellowColor].CGColor,
(id)[UIColor redColor].CGColor];
[leftGradient setLocations:@[@0.3, @0.9, @1]];
CAGradientLayer *rightGradient = [CAGradientLayer layer];
rightGradient.frame = CGRectMake(self.bounds.size.width / 2, -layerWidth/2, self.bounds.size.width / 2 + layerWidth/2, self.bounds.size.height + layerWidth);
rightGradient.colors = @[(id)[UIColor yellowColor].CGColor,
(id)[UIColor greenColor].CGColor];
[rightGradient setLocations:@[@0.3, @0.9, @1]];
[gradientLayer addSublayer:leftGradient];
[gradientLayer addSublayer:rightGradient];
[gradientLayer setMask:_topLayer];
[self.layer addSublayer:gradientLayer];
demo.gif
github下载地址 ZXYProgressView