画饼状图-UIBezierPath

这是看的传值博客视频写的代码
首先,得到一个数组,数组里面放的是一系列数字.在这里,随机取得100以内的4个数字.

// 随机数组
- (NSArray *)arrRandom {
    int total = 100;
    NSMutableArray *arrM = [NSMutableArray array];
    int temp = 0;
    for (int i = 0; i < 3; i++) {
        temp = arc4random_uniform(total);
        [arrM addObject:@(temp)];
        total -= temp;
    }
    if (temp) {
        [arrM addObject:@(temp)];
    }
    return arrM;
}

而且,为了画出的图分辨出来,给他们添加不同的颜色

- (UIColor *)colorRandom {
    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];
}

开始画图

// 注意:drawRect不能手动调用,因为图形上下文我们创建不了,只能有系统帮我们创建,并且传递给我们
- (void)drawRect:(CGRect)rect {
    NSArray *arr = [self arrRandom];
    CGFloat radius = rect.size.width * 0.5;
    CGPoint center = CGPointMake(radius, radius);

    CGFloat startA = 0;
    CGFloat angel = 0;
    CGFloat endA = 0;

    for (int i = 0; i < arr.count; i++) {
        startA = endA;
        angel = [arr[i] doubleValue] / 100.0 * M_PI * 2;
        endA = startA + angel;
        /*
         * Center:圆心
         * startAngle:弧度
         * clockwise:YES:顺时针 NO:逆时针
         */
        UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];
        // 添加一根线到圆心
        [path addLineToPoint:center];
        // 给封闭的空间添加颜色
        [[self colorRandom] set];
        // 渲染
        [path stroke];
        // 填充:必须是一个封闭的路径,默认就会自动关闭路径
        [path fill];
    }
}

当点击的时候,改变饼状图

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 重绘:系统会先创建与 View 相关联的上下文,然后在调drawRect
    [self setNeedsDisplay];
}

效果图
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值