iOS学习交流控件封装动画

使用贝塞尔曲线画饼图

2016-02-18  本文已影响663人  芝麻绿豆

没什么好说的上代码吧!

利用代理和数据源,让用户设置数据和半径及相应的颜色;在相应的控制器内实现代理方法和数据源方法
@protocol CrlViewDelegate <NSObject>
- (CGFloat)centerCircleRadius;

@end

@protocol CrlViewDataSource <NSObject>
@required
- (int)numberOfSlicesInPieChartView:(crlView *)pieChartView;
- (double)pieChartView:(crlView *)pieChartView valueForSliceAtIndex:(NSUInteger)index;
- (UIColor *)pieChartView:(crlView *)pieChartView colorForSliceAtIndex:(NSUInteger)index;
@optional
- (NSString*)pieChartView:(crlView *)pieChartView titleForSliceAtIndex:(NSUInteger)index;

@end
在- (void)drawRect:(CGRect)rect方法内绘图;
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGFloat theHalf = rect.size.width/2;
    CGFloat lineWidth = theHalf;
    lineWidth -= [self.delegate centerCircleRadius];
    CGFloat radius = theHalf-lineWidth/2;
    
    /*圆心坐标*/
    CGPoint center = CGPointMake(theHalf, rect.size.height/2);
    
    float startAngle = - M_PI_2;
    float endAngle = 0.0f;
    
    double sum = 0.0f;
    /*饼状图中切片个数*/
    int slicesCount = [self.datasource numberOfSlicesInPieChartView:self];

    for (int i = 0; i < slicesCount; i++) {
        sum += [self.datasource pieChartView:self valueForSliceAtIndex:i];
    }
    for (int i = 0; i < slicesCount; i ++) {
        static double blckAngle = 0.0f;
        double nextAngle = [self.datasource pieChartView:self valueForSliceAtIndex:i] * (2 * M_PI)/ sum;
        UIColor *fillColor = [self.datasource pieChartView:self colorForSliceAtIndex:i];
        NSString *title;
        if ([self.datasource respondsToSelector:@selector(pieChartView:titleForSliceAtIndex:)]) {
             title = [self.datasource pieChartView:self titleForSliceAtIndex:i];
        }
        UIBezierPath *path;
        if (i == 0) {
            
            path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startAngle endAngle:nextAngle clockwise:YES];
            [fillColor setFill];
        }
        else if(i == slicesCount - 1){
        
            path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:nextAngle endAngle:endAngle clockwise:YES];
        }
        else{
        
            path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:blckAngle endAngle:nextAngle clockwise:YES];
        }

        blckAngle = nextAngle;
        [path addLineToPoint:center];
        [path closePath];
        [fillColor setFill];
        CGContextAddPath(context, path.CGPath);
        CGContextDrawPath(context, kCGPathFillStroke);
    }
效果图

可以在下方添加一下说明绘制上去;

上一篇下一篇

猜你喜欢

热点阅读