UIView 扇形

2016-08-15  本文已影响168人  xgou
- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    if(self.rateArray.count == 0) {
        return;
    }
    
    double(^angleConverRadian)(double) = ^(double angle) {
        return M_PI / 180 * angle;
    };
    
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    CGContextBeginPath(contextRef);
    
    __block CGFloat startRadian = -M_PI / 2;
    __block CGFloat startAngle = 0;
    CGFloat w = CGRectGetWidth(self.frame),
    h = CGRectGetHeight(self.frame),
    radius = MIN(w, h) / 2;
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:self.bounds];
    [shapeLayer setPosition:CGPointMake(w/2, h/2)];
    [shapeLayer setStrokeColor:self.backgroundColor.CGColor];
    [shapeLayer setLineWidth:3.0f];
    [shapeLayer setLineJoin:kCALineJoinRound];
    
    CGMutablePathRef path = CGPathCreateMutable();
    [self.rateArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CGContextSetLineJoin(contextRef, kCGLineJoinRound);
        CGContextMoveToPoint(contextRef, w / 2, h / 2);
        //这个obj要约定2个元素,一个是角度,和颜色。
        double angle = [obj[@"angle"] floatValue];
        double radian = angleConverRadian([obj[@"angle"] floatValue]);
        
        CGContextAddArc(contextRef, w / 2, h / 2, radius, startRadian, startRadian + radian, NO);
        
        CGContextSetFillColorWithColor(contextRef, [obj[@"color"] CGColor]);
        
        CGContextDrawPath(contextRef, kCGPathFill);
        CGPoint beginPoint = CGPointZero;
        
        if(startAngle <= 90) {
            beginPoint = CGPointMake(sin(angleConverRadian(startAngle)) * radius + radius, radius - cos(angleConverRadian(startAngle)) * radius);
        
        }
        
        else if (startAngle <= 180) {
        
            beginPoint = CGPointMake(sin(angleConverRadian(180 - startAngle)) * radius + radius, cos(angleConverRadian(180 - startAngle)) * radius + radius);
        
        }
        
        else if (startAngle <= 270) {
        
            beginPoint = CGPointMake(radius - sin(angleConverRadian(270 - startAngle)) * radius, cos(angleConverRadian(270 - startAngle)) * radius + radius);
        
        }
        
        else if (startAngle <= 360) {
        
            beginPoint = CGPointMake(radius - sin(angleConverRadian(360 - startAngle)) * radius, cos(360 - startAngle) * radius);
        
        }
        
        CGPathMoveToPoint(path, NULL, beginPoint.x, beginPoint.y);
        
        CGPathAddLineToPoint(path, NULL, w / 2, h / 2);
        
        startRadian += radian;
        
        startAngle += angle;
    
    }];
    
    shapeLayer.path = path;
    
    CGPathRelease(path);
    
    [[self layer] addSublayer:shapeLayer];

}
上一篇下一篇

猜你喜欢

热点阅读