先上效果图
@interface PieView : UIView
-(instancetype)initWithCenter:(CGPoint)center radius:(CGFloat)radius bgColor:(UIColor *)bgColor andstartAngle:(CGFloat)startAngle andendAngle:(CGFloat)endAngle;
@end
-(instancetype)initWithCenter:(CGPoint)center radius:(CGFloat)radius bgColor:(UIColor *)bgColor andstartAngle:(CGFloat)startAngle andendAngle:(CGFloat)endAngle {
self = [super init];
if (self) {
//设置self的frame和center
self.backgroundColor = bgColor;
self.frame = CGRectMake(0, 0, radius * 2, radius * 2);
self.center = center;
//特别注意:贝塞尔曲线的radius必须为self高度的四分之一,CAShapeLayer的线宽必须为self高度的二分之一
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(radius, radius) radius:radius / 2 startAngle:startAngle endAngle:endAngle clockwise:YES];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.path = path.CGPath;
maskLayer.fillColor = [UIColor clearColor].CGColor;
maskLayer.strokeColor = bgColor.CGColor;
maskLayer.lineWidth = radius; //等于半径的2倍,以圆的边缘为中心,向圆内部伸展一个半径,向外伸展一个半径,所以看上去以为圆的半径是self高度的一半。
self.layer.mask = maskLayer;
}
return self;
}
CGPoint point = CGPointMake(150, 150);
PieView *redView = [[PieView alloc] initWithCenter:point radius:50 bgColor:[UIColor redColor] andstartAngle:-M_PI/2 andendAngle:0.0];
[self.view addSubview:redView];
PieView *blueView = [[PieView alloc] initWithCenter:point radius:70 bgColor:[UIColor blueColor] andstartAngle:0.0f andendAngle:M_PI*3/2];
[self.view addSubview:blueView];
网友评论