iOS畫餅圖

扇形易畫,扇形的中心點不易找。

找扇形中心點的算法分析

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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容