IOS開發之——繪製餅狀圖

文章搬運 來源:blog.csdn.net/Calvin_zhou…面試

做者:PGzxcmarkdown

對iOS開發感興趣,能夠看一下做者的iOS交流羣:812157648,你們能夠在裏面吹水、交流相關方面的知識,羣裏還有我整理的有關於面試的一些資料,歡迎你們加羣,你們一塊兒開車dom

一 概述

  • 按照1:1:2的份額劃分圓形
  • 開始角度爲0度,旋轉角度爲份額2π(360度),結束角度爲開始角度+旋轉角度
  • 給每分餅狀圖設置不一樣的顏色
  • 點擊圖形,餅狀圖切換顏色

二 餅狀圖劃分

startA=0;
angle=25/100.0*M_PI*2;
endA=startA=angle;

複製代碼

三 功能開發

3.1 代碼

pieView

- (void)drawRect:(CGRect)rect {
    // Drawing code
    NSArray *data=@[@25,@25,@50];
    //1.獲取上下文
    CGContextRef ctx=UIGraphicsGetCurrentContext();
    CGPoint center=CGPointMake(125, 125);
    CGFloat radius=120;
    CGFloat startA=0;
    CGFloat angle=0;
    CGFloat endA=0;

    for (NSNumber *number in data) {
        //2.拼接路徑
        startA=endA;
        angle=number.intValue/100.0*M_PI*2;
        endA=startA+angle;

        UIBezierPath *path=[UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
        [path addLineToPoint:center];
        [[UIColor randomColor]set];
        //3.把路徑添加到上下文
        CGContextAddPath(ctx, path.CGPath);
        //4.渲染
        CGContextFillPath(ctx);
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self setNeedsDisplay];
}

複製代碼

UIColor+RandomColor(隨機顏色工具)

#import "UIColor+RandomColor.h"

@implementation UIColor (RandomColor)
+(UIColor *)randomColor
{
    CGFloat r=arc4random_uniform(256)/255.0;
    CGFloat g=arc4random_uniform(256)/255.0;
    CGFloat b=arc4random_uniform(256)/255.0;
    return  [UIColor colorWithRed:r green:g blue:b alpha:1];

}
@end

複製代碼

3.2 效果圖

相關文章
相關標籤/搜索