iOS画饼图

作者: 孟圆的笔记 | 来源:发表于2017-06-21 08:10 被阅读37次

扇形易画,扇形的中心点不易找。

找扇形中心点的算法分析

120336-7f77dcb0cc28e0ef.png

****注意****:此找扇形中点算法,是从-π/2开始画扇形的。原文

610137-8545baa62b507821.jpeg

以红色部分开始为例计算
r:扇形半径
center:PieView中心位置
start:开始位置,范围[0,1]
end:结束位置,范围[0,1]
⍺:相对于y轴(-π/2)扇形中间位置的角度
  ⍺ = 2 * π * (start + 1/2.0 * (end - start)) = π * (start + end)
𝛥x:labelCenter到y轴距离
  𝛥x = 1/2.0 * r * sin(⍺)
𝛥y:labelCenter到y轴距离
  𝛥y = 1/2.0 * r * cos(⍺)
labelCenter:百分比label的center
  labelCenterX = center.x + 𝛥x
  labelCenterY = center.y - 𝛥y


DrawView.m文件:

- (void)drawRect:(CGRect)rect {
    CGPoint center = CGPointMake(rect.size.width*0.5, rect.size.height*0.5); //圆心
    CGFloat margin = 80; //饼图与view外边框的距离
    CGFloat r = rect.size.width*0.5-margin; //半径
    
    NSArray *arr = @[@0.05, @0.15, @0.2, @0.3, @0.15, @0.15]; //加起来等于1
    
    for (int i=0; i<arr.count; i++) {
        
        CGFloat start = 0;
        
        int j = i;
        while (j-- > 0) {
            start += [arr[j] doubleValue];
        }
        
        CGFloat end = [arr[i] doubleValue]+start;
        
        
        //画扇形
        //注意:以上找扇形中点算法,是从-π/2开始画扇形的
        UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:r startAngle:2*M_PI*start-M_PI_2 endAngle:2*M_PI*end-M_PI_2 clockwise:YES];
        [path addLineToPoint:center];
        [[self randomColor] set];
        [path fill];
        
        
        //找扇形中点
        CGFloat halfAngle = M_PI * (start + end); //当前扇形弧度的一半
        CGFloat sectorCenterX = r*0.8 * sinf(halfAngle) + center.x;
        CGFloat sectorCenterY = -r*0.8 * cosf(halfAngle) + center.y;
        CGPoint sectorCenter = CGPointMake(sectorCenterX, sectorCenterY);
        
        
        //求第二点
        CGFloat d = 35; //第二点到圆的距离
        CGFloat x2 = (r+d) * sinf(halfAngle) + center.x;
        CGFloat y2 = -(r+d) * cosf(halfAngle) + center.y;
        CGPoint point2 = CGPointMake(x2, y2);
        
        //画引线
        path = [UIBezierPath bezierPath];
        [path moveToPoint:sectorCenter];
        [path addLineToPoint:point2];
        [path addLineToPoint:CGPointMake(x2>=center.x?x2+37:x2-37, y2)];
        [[UIColor whiteColor] set];
        [path stroke];
        
        //画文字
        NSString *text = [NSString stringWithFormat:@"%.1f%%", [arr[i] doubleValue]*100];
        [text drawAtPoint:CGPointMake(x2>=center.x?x2+3:x2-37, y2-14) withAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    }
}

效果图:

Snip20170622_1.png

相关文章

网友评论

    本文标题:iOS画饼图

    本文链接:https://www.haomeiwen.com/subject/dfvaqxtx.html