iOS 画饼状图

画饼状图其实就是画扇形,比如我们需要实现下面这个效果
这里写图片描述

画图思路:
1、根据数据源的个数来判断需要画多少个扇形(比如:25,15,30,10,20,说明我们要画5个扇形)
2、根据数据源判断每组数据占一个圆的多少(比如,startA:0,angle:25/100.0 *M_PI *2,endA:startA+angle)
3、下一个扇形的大小起点就是上一个扇形的结束点(比如,startA:end,angle:15/100.0 *M_PI *2,endA:startA+angle)
4、以此类推。。。


@interface PieChartView:UIView
@end

@implementation PieChartView

- (void)drawRect:(CGRect)rect{

    //数据源
    NSArray *numberArray = @[@25,@15,@30,@10,@20];
    NSArray *colorArray = @[[UIColor redColor],[UIColor yellowColor],[UIColor purpleColor],[UIColor greenColor],[UIColor orangeColor]];

    //半径
    CGFloat radius = rect.size.width / 2;
    //中心点
    CGPoint center = CGPointMake(radius, radius);

    //起始角度
    CGFloat startA = 0;
    //弧度
    CGFloat angle = 0;
    //结束角度
    CGFloat endA = 0;


    for (int i = 0; i < numberArray.count; i ++) {

        startA = endA;
        angle = [numberArray[i] floatValue] / 100.0 * M_PI * 2;
        endA = startA + angle;

        [self pieChartWithCenter:center withRadius:radius withStartAngle:startA withEndAngle:endA withColor:colorArray[i]];

    }

}

-(void)pieChartWithCenter:(CGPoint)center withRadius:(CGFloat)radius withStartAngle:(CGFloat)startA withEndAngle:(CGFloat)endA withColor:(UIColor*)color{

    //画弧
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];

    //添加一根线到圆心
    [path addLineToPoint:center];

    //设置颜色(描边和填充通用)
    [color setFill];

    [path fill];
}


@end

最后,附上相关的demo,Git:(https://github.com/hejiasu/Drawing)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值