1. 程式人生 > >自定義餅圖的繪製

自定義餅圖的繪製

如何畫一個餅圖, 來實現資料展示的視覺化

  • PieChartView.h
#import <UIKit/UIKit.h>

@interface PieChartView : UIView

@end
  • PieChartView.m
#import "PieChartView.h"

@implementation PieChartView

- (void)drawRect:(CGRect)rect {

    CGFloat w = self.bounds.size.width;
    CGFloat h = self.bounds.size.height
; //資料陣列 NSArray *array = @[@25,@30,@45]; //顏色陣列 NSArray *colorArray = @[[UIColor redColor], [UIColor greenColor], [UIColor yellowColor]]; CGContextRef ctx =UIGraphicsGetCurrentContext(); //中心點 CGPoint center = CGPointMake(w * 0.5, h * 0.5); //半徑 CGFloat radius = w * 0.5 - 5
; //起點角度 CGFloat startA = 0; //終點角度 CGFloat endA = 0; //掃過角度範圍 CGFloat angle = 0; for (int i = 0; i < array.count; i ++) { startA = endA; angle = [array[i] integerValue] / 100.0 * M_PI * 2; endA = startA + angle; //弧形路徑 //clockwise: 是否是按照時鐘的方向旋轉(是否順時針)
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES]; //連線中心, 構成扇形 [path addLineToPoint:center]; //填充顏色 [(UIColor *)colorArray[i] set]; CGContextAddPath(ctx, path.CGPath); // 將上下文渲染到檢視 CGContextFillPath(ctx); } } @end