ios饼图

这里写图片描述
这里写图片描述

AppDelegate默认

ViewController.h默认

ViewController.m

#import "ViewController.h"
#import "KMView.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 加载一个 xib 怎么加载??
    KMView * pieView = [KMView kmView];
    //比例分配
    pieView.array = @[@0.2,@0.2,@0.1,@0.1,@0.4];
    pieView.frame = CGRectMake(0, 0, 300, 300);
    [self.view addSubview:pieView];





}

KMView.xib

这里写图片描述

KMView.h

#import <UIKit/UIKit.h>

@interface KMView : UIView

@property (nonatomic ,strong) NSArray *array;

// 类方法:好处,不用创建对象.能用类方法,就不用,实例方法.

+ (instancetype)kmView;

@end

KMView.m

#define KSize self.bounds.size

#import "KMView.h"

@implementation KMView
// 类方法,快速创建
+ (instancetype)kmView {

    return  [[NSBundle mainBundle] loadNibNamed:@"KMView" owner:nil options:nil].firstObject;
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // 画图.   算法. cos sin arctan
    // 把这个参数暴露给用户.
   // NSArray * arr = @[@0.3,@0.4,@0.2,@0.1];
//                     108  90  108    36
    CGFloat start = 0;
    CGFloat end = 0;
    for (int i = 0; i < self.array.count; i ++) {
        // 计算当前的扇形的结束位置.
        end = 2 * M_PI * [self.array[i] floatValue] + start;  // 单纯的就是一个角度

        // 画扇形
//        MAX(<#A#>, <#B#>); 返回两个中的最大的一个
//        MIN(<#A#>, <#B#>)  返回像个中的最小的一个

        UIBezierPath * path  = [UIBezierPath bezierPathWithArcCenter:[self arcCenter] radius:MIN(KSize.width, KSize.height) * 0.5 - 10 startAngle:start endAngle:end clockwise:30];


        // 往圆心连线
        [path addLineToPoint:[self arcCenter]];

        // 设置颜色
        [[self randomColor] set];

        // 渲染
        [path fill];

        // 在当前绘制结束的时候,把结束的位置,下一个的开始.
        start = end;
    }


}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 重绘
    [self setNeedsDisplay];

}

// 返回中心点的 方法
- (CGPoint)arcCenter
{
    return CGPointMake(KSize.width * 0.5, KSize.height * 0.5);

}


// 随机颜色
- (UIColor *)randomColor
{
    CGFloat r = arc4random() % 256 / 255.0;
    CGFloat g = arc4random() % 256 / 255.0;
    CGFloat b = arc4random() % 256 / 255.0;
    return [UIColor colorWithRed:r green:g blue:b alpha:1];
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值