UIBezierPath绘制柱状图、折线图和饼状图

最近用UIBezierPath绘制了一些图形,像柱状图、折线图和饼状图之类的图形。先上效果图:

 

基本原理:

  • 利用UIBezierPath能够创建基于矢量路径的特性来绘制图形的路径,然后将UIBezierPathCAShapeLayer建立关系,让后者在前者提供的路径中进行渲染,最后生成我们所需的各种图形。而且可以给CAShapeLayer添加动画特效。

一、柱状图

实现思路:

  • 对数据源进行分析,获取数据源的最大值,以及最大值和柱状图高度的比例,用于其他数据等比例显示。数据源为:
- (NSArray *)topArray {
    return @[@"342",@"900",@"505",@"1780",@"1450",@"30",@"1000”];
}
- (NSArray *)bottomArray {
    return @[@"1月",@"2月",@"3月",@"4月",@"5月",@"6月",@"7月”];
}

获取数据源最大值以及比例:

//获取数据最大值
float max = [[self.topArray valueForKeyPath:@"@max.intValue"] floatValue];
//获取比例大小
float scale = (K_HEIGHT-K_LABEL_HEIGHT*2)/max;
  • 然后利用UIBezierPath绘制单个柱状的起点和终点的连线:
//柱状图
UIBezierPath * bePath = [UIBezierPath bezierPath];
//起点
[bePath moveToPoint:CGPointMake(K_WIDTH/(count*2)+K_WIDTH/count*i, K_HEIGHT-K_LABEL_HEIGHT)];
//终点
[bePath addLineToPoint:CGPointMake(K_WIDTH/(count*2)+K_WIDTH/count*i, K_HEIGHT-K_LABEL_HEIGHT-[self.topArray[i] floatValue]*scale)];
[bePath stroke];
  • 创建CAShapeLayer(其属性作用在下面分类中有说明),并与UIBezierPath建立关系,即设置path属性:
//添加CAShapeLayer
_shaLayer = [CAShapeLayer layerWithFillColor:[UIColor clearColor].CGColor strokeColor:[UIColor greenColor].CGColor strokeStart:0.0f strokeEnd:1.0f zPosition:1 lineWidth:30.0f path:bePath.CGPath];
 [self.layer addSublayer:_shaLayer];

CAShapeLayer的分类方法为:

@implementation CAShapeLayer (Category)

/** CAShapeLayer
 * @param fillColor   填充颜色
 * @param strokeColor 填充路径的描边轮廓的颜色
 * @param strokeStart 表示路径的起点,在[0,1]的范围内
 * @param strokeEnd   表示路径的终点,在[0,1]的范围内
 * @param zPosition   表示在superlayer中的位置
 * @param lineWidth   填充路径的线宽
 * @param path        表示要呈现形状的路径
 */
+ (CAShapeLayer *)layerWithFillColor:(CGColorRef)fillColor strokeColor:(CGColorRef)strokeColor strokeStart:(CGFloat)strokeStart strokeEnd:(CGFloat)strokeEnd zPosition:(CGFloat)zPosition lineWidth:(CGFloat)lineWidth path:(CGPathRef)path {
    CAShapeLayer * layer = [CAShapeLayer layer];
    layer.fillColor = fillColor;
    layer.strokeColor = strokeColor;
    layer.strokeStart = strokeStart;
    layer.strokeEnd = strokeEnd;
    layer.zPosition = zPosition;
    layer.lineWidth = lineWidth;
    layer.path  = path;
    return layer;
}
@end
  • 为创建的CAShapeLayer添加动画特效:
//动画
- (void)startStroke {
    [_shaLayer addAnimation:self.pathAnimation forKey:@"strokeEndAnimation”];
}

动画方法为:

//动画
- (CABasicAnimation *)pathAnimation {
    CABasicAnimation * pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd”];
    pathAnimation.duration = 2.0f;
    pathAnimation.fromValue = @0.0f;//动画开始位置
    pathAnimation.toValue = @1.0f;//动画停止位置
    pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];//添加动画样式
    return pathAnimation;
}
  • 为每个柱状创建上下数据展示label
//上label
[self addSubview:[UILabel labelWithFrame:CGRectMake(K_WIDTH/count*i, K_HEIGHT-60-[self.topArray[i] floatValue]*scale, K_WIDTH/count, K_LABEL_HEIGHT) text:self.topArray[i] textColor:[UIColor redColor] textAlignment:NSTextAlignmentCenter font:15]];
//下label
[self addSubview:[UILabel labelWithFrame:CGRectMake(K_WIDTH/count*i, K_HEIGHT-K_LABEL_HEIGHT, K_WIDTH/count, K_LABEL_HEIGHT) text:self.bottomArray[i] textColor:[UIColor blackColor] textAlignment:NSTextAlignmentCenter font:13]];
  • 最后按数据源个数对以上控件进行循环创建。

最终实现效果为:

柱状图.gif

二、折线图

折线图的实现方法和柱状图的实现方法类似,主要在于折线图需要创建一个坐标体系,并对数据源中每个坐标点进行连线绘制。直接上代码(数据源和柱状图一样):

#import “BrokenView.h”
#import "UILabel+Category.h”

#define K_WIDTH          CGRectGetWidth(self.frame)
#define K_HEIGHT         CGRectGetHeight(self.frame)
#define K_LABEL_HEIGHT   30
#define K_ACROSS_NUM     6 //横线默认条数
@implementation BrokenView {
    CAShapeLayer * _shaLayer;
}

- (instancetype)initWithFrame:(CGRect)frame topArray:(NSArray *)topArray bottoArray:(NSArray *)bottomArray {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        self.topArray = topArray;
        self.bottomArray = bottomArray;
    }
    return self;
}

//动画
- (void)startStroke {
    [_shaLayer addAnimation:self.pathAnimation forKey:@"strokeEndAnimation”];
}

- (void)drawRect:(CGRect)rect {
    NSUInteger count = self.topArray.count;
    if (count<1) return;
    //获取数据最大值
    float max = [[self.topArray valueForKeyPath:@"@max.intValue"] floatValue];//获取比例大小
    float scale = (K_HEIGHT-K_LABEL_HEIGHT*2)/max;//上下两个label高度和
    
    //绘制坐标系
    for (int i=0; i<K_ACROSS_NUM; i++) {
        //横线
        UIBezierPath * across = [UIBezierPath bezierPath];
        [across moveToPoint:CGPointMake(0, (K_HEIGHT-K_LABEL_HEIGHT)/K_ACROSS_NUM*(i+1))];
        [across addLineToPoint:CGPointMake(K_WIDTH, (K_HEIGHT-K_LABEL_HEIGHT)/K_ACROSS_NUM*(i+1))];
        [[UIColor greenColor] set];
        [across stroke];
    }
    
    for (int j=0; j<count; j++) {
        //竖线
        UIBezierPath * vertical = [UIBezierPath bezierPath];
        [vertical moveToPoint:CGPointMake(K_WIDTH/(count*2)+K_WIDTH/count*j, K_HEIGHT-K_LABEL_HEIGHT)];
        [vertical addLineToPoint:CGPointMake(K_WIDTH/(count*2)+K_WIDTH/count*j, 0)];
        [[UIColor greenColor] set];
        [vertical stroke];
        
        //绘制各坐标点
        UIBezierPath * point = [UIBezierPath bezierPathWithArcCenter:CGPointMake(K_WIDTH/(count*2)+K_WIDTH/count*j, K_HEIGHT-K_LABEL_HEIGHT-[self.topArray[j] floatValue]*scale) radius:5.0f startAngle:-M_PI endAngle:M_PI*3 clockwise:YES];
        CAShapeLayer * pointLayer = [CAShapeLayer layerWithFillColor:[UIColor blueColor].CGColor strokeColor:[UIColor clearColor].CGColor strokeStart:0.0f strokeEnd:1.0f zPosition:0 lineWidth:0.0f path:point.CGPath];
        [self.layer addSublayer:pointLayer];
        
        //上label
        [self addSubview:[UILabel labelWithFrame:CGRectMake(K_WIDTH/count*j, K_HEIGHT-60-[self.topArray[j] floatValue]*scale, K_WIDTH/count, K_LABEL_HEIGHT) text:self.topArray[j] textColor:[UIColor redColor] textAlignment:NSTextAlignmentCenter font:15]];
        //下label
        [self addSubview:[UILabel labelWithFrame:CGRectMake(K_WIDTH/count*j, K_HEIGHT-K_LABEL_HEIGHT, K_WIDTH/count, K_LABEL_HEIGHT) text:self.bottomArray[j] textColor:[UIColor blackColor] textAlignment:NSTextAlignmentCenter font:13]];
    }
    //绘制折线
    UIBezierPath * broPath = [UIBezierPath bezierPath];
    [broPath moveToPoint:CGPointMake(K_WIDTH/(count*2), K_HEIGHT-K_LABEL_HEIGHT-[self.topArray[0] floatValue]*scale)];
    for (int j=1; j<count; j++) {
        [broPath addLineToPoint:CGPointMake(K_WIDTH/(count*2)+K_WIDTH/count*j, K_HEIGHT-K_LABEL_HEIGHT-[self.topArray[j] floatValue]*scale)];
    }
    [broPath stroke];
    _shaLayer = [CAShapeLayer layer];
    _shaLayer.lineWidth = 2.0f;
    _shaLayer.fillColor = [UIColor clearColor].CGColor;
    _shaLayer.strokeColor = [UIColor blueColor].CGColor;
    _shaLayer.path = broPath.CGPath;
    [self.layer addSublayer:_shaLayer];
    
    [self startStroke];
}
@end

最终实现效果为:

折线图.gif

三、饼状图

实现思路:

  • 首先设置饼状图中心点以及半径:
//设置饼状图中心点
CGFloat centerX = K_WIDTH * 0.5f;
CGFloat centerY = K_HEIGHT * 0.5f;
CGPoint centerPoint = CGPointMake(centerX, centerY);
//设置半径
CGFloat radius = MIN(centerX, centerY) * 0.5f;//MIN(A,B)为获取两者最小值
  • 设置数据源:
- (NSArray *)pieArray {
    return @[@"70",@"60",@"100",@"50",@"80"];
}
- (NSArray *)colorArray {
    return @[[UIColor redColor],[UIColor purpleColor],[UIColor blueColor],[UIColor orangeColor],[UIColor blackColor]];
}
  • 获取数据源数据总和,用于后面扇形划分比例:
//获取展示数据总和
CGFloat nums = 0.0f;
for (int i=0; i<self.dataArray.count; i++) {
    nums += [self.dataArray[i] floatValue];
}
  • 创建一个背景圆,用于后期添加动画特效:
    //绘制背景圆的路径
    UIBezierPath * backPath = [UIBezierPath bezierPathWithArcCenter:centerPoint
                                                             radius:radius
                                                         startAngle:-M_PI_2
                                                           endAngle:M_PI_2*3
                                                          clockwise:YES];
    _backLayer = [CAShapeLayer layerWithFillColor:[UIColor clearColor].CGColor
                                      strokeColor:[UIColor greenColor].CGColor
                                      strokeStart:0.0f
                                        strokeEnd:1.0f
                                        zPosition:1
                                        lineWidth:radius * 2.0f
                                             path:backPath.CGPath];

UIBezierPath绘制圆形方法+ (instancetype)bezierPathWithArcCenter:(CGPoint)center radius:(CGFloat)radius startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle clockwise:(BOOL)clockwise;中参数如下:center是弧线中心点的坐标; radius是弧线所在圆的半径; startAngle是弧线开始的角度值; endAngle是弧线结束的角度值; clockwise表示是否顺时针画弧线。

  • UIBezierPath绘制各个扇形的路径,和背景圆路径一样:
//绘制各个扇形的路径
    UIBezierPath * subPath = [UIBezierPath bezierPathWithArcCenter:centerPoint
                                                            radius:radius
                                                        startAngle:-M_PI_2
                                                          endAngle:M_PI_2*3
                                                         clockwise:YES];
  • 分别获取饼状图中每个扇形的起点strokeStart和终点strokeEnd,并按数据源的个数循环创建每个扇形的CAShapeLayer,并与subPath相关联,并以此获取扇形的形状。
 //设置各个扇形开始和结束位置
    CGFloat start = 0.0f;
    CGFloat end = 0.0f;
    for (int i=0; i<self.dataArray.count; i++) {
        end = [self.dataArray[i] floatValue]/nums + start;
        CGColorRef strokeColor = (!self.colorArray ||  self.colorArray.count == 0 || i>self.colorArray.count-1) ? [UIColor purpleColor].CGColor : ((UIColor *)self.colorArray[i]).CGColor;
        CAShapeLayer * subLayer = [CAShapeLayer layerWithFillColor:[UIColor clearColor].CGColor
                                                       strokeColor:strokeColor
                                                       strokeStart:start
                                                         strokeEnd:end
                                                         zPosition:2
                                                         lineWidth:radius * 2.0f
                                                              path:subPath.CGPath];
        [self.layer addSublayer:subLayer];
        
        //百分比label
        CGFloat angle = M_PI * (start + end);//扇形角度
        CGFloat labelCenterX = centerX * 0.5f * sinf(angle) + centerX;
        CGFloat labelCenterY = -centerX * 0.5f * cosf(angle) + centerY;
        UILabel * label = [UILabel labelWithFrame:CGRectMake(0, 0, radius * 0.8f, radius * 0.3f) text:[NSString stringWithFormat:@"%@  %ld%%",self.dataArray[i],(NSInteger)((end-start+0.005)*100)] textColor:[UIColor redColor] textAlignment:NSTextAlignmentCenter font:15];
        label.center = CGPointMake(labelCenterX, labelCenterY);
        label.backgroundColor = [UIColor whiteColor];
        label.layer.zPosition = 3;
        [self addSubview:label];
        
        start = end;
    }

其中以每个扇形的中轴线的中点为中心点来创建的label用于显示扇形的比例。中心点坐标是利用三角形的正弦函数和余弦函数来确定的。

  • 最后为背景圆的Layer添加动画:
//动画
- (void)startStroke {
    [_backLayer addAnimation:self.pathAnimation forKey:@"circleAnimation”];
}

最终实现效果为:

 

饼状图.gif


Demo地址:UIBezierPath绘制柱状图、折线图和饼状图

作者:wuyukobe
链接:https://www.jianshu.com/p/e37493cf093e
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值