iOS餅狀圖的實現~畫~

核心函數是:CGContextAddArc(CGContextRef c, CGFloat x, CGFloat y, CGFloat radius, CGFloat startAngle, CGFloat endAngle, int clockwise)函數

* CGContextRef:圖形上下文spa

* x,y: 開始畫的座標code

* radius: 半徑blog

* startAngle, endAngle: 開始的弧度,結束的弧度it

* clockwise: 畫的方向(順時針,逆時針)io

#define PI 3.14159265358979323846
#define radius 100
#import "BingView.h"

@implementation BingView
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

static inline float radians(double degrees)
{
    return degrees * PI / 180;
}

/**
 *  關鍵函數
 *
 *  @param ctx         圖形上下文
 *  @param point       開始畫的座標
 *  @param angle_start 開始的弧度
 *  @param angle_end   結束的弧度
 *  @param color       填充顏色
 *
 *  @return ok
 */
static inline void drawArc(CGContextRef ctx, CGPoint point, float angle_start, float angle_end, UIColor* color) {
    CGContextMoveToPoint(ctx, point.x, point.y);
    CGContextSetFillColor(ctx, CGColorGetComponents( [color CGColor]));
    CGContextAddArc(ctx, point.x, point.y, radius,  angle_start, angle_end, 0);
//    CGContextClosePath(ctx);
    CGContextFillPath(ctx);
}

- (void)drawRect:(CGRect)rect {
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextClearRect(ctx, rect);

    float angle_start = radians(0.0);
    float angle_end = radians(121.0);
    drawArc(ctx, self.center, angle_start, angle_end, [UIColor yellowColor]);
    
    angle_start = angle_end;
    angle_end = radians(228.0);
    drawArc(ctx, self.center, angle_start, angle_end, [UIColor greenColor]);
    
    angle_start = angle_end;
    angle_end = radians(260);
    drawArc(ctx, self.center, angle_start, angle_end, [UIColor orangeColor]);
    
    angle_start = angle_end;
    angle_end = radians(360);
    drawArc(ctx, self.center, angle_start, angle_end, [UIColor purpleColor]);
}
@end
相關文章
相關標籤/搜索