iOS利用貝塞爾曲線和CAShapeLayer創(chuàng)建縱向分段顏色帶動(dòng)畫柱狀圖

前言

效果圖

  • 柱子的高度是到頂部的,由于柱子的顏色和View背景色一致了,無法看清,更改下背景色就能看到了,柱子的最大值是1440,可以根據(jù)自己需求進(jìn)行更改 這個(gè)屬性 MAX_TIME
![MKChart.gif](http://upload-images.jianshu.io/upload_images/2597026-70c5424b0f14cbef.gif)
  • 本文主要參考了PNChart ,有興趣的同學(xué)可以去學(xué)習(xí)下
    廢話不說了,直接上代碼

  • 主要分為3個(gè)類

  • MKBar: 是單個(gè)柱子,包括繪制和數(shù)據(jù)的分段處理

  • BarLayerView : 主要是繪制多個(gè)柱子,對(duì)柱子進(jìn)行更新等

  • ViewController : 展示界面

MKBar

MKBar.h

#import <UIKit/UIKit.h>

@interface MKBar : UIView

@property (nonatomic,copy)NSString *titleStr;//標(biāo)題

@property (nonatomic,strong)NSMutableArray *dataArr;//數(shù)據(jù)  注意數(shù)據(jù)格式

@end

MKBar.m

#define MAX_TIME 1440
#define RGB(r,g,b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1]
@interface MKBar ()

@property (nonatomic) CATextLayer* textLayer;//標(biāo)題Layer

@property (nonatomic,strong)NSMutableArray *barArr;//柱子上面進(jìn)度數(shù)據(jù)

@property (nonatomic,assign)float totalNum;//總的進(jìn)度時(shí)間

@property (nonatomic,strong)UILabel *titleLab;//下面標(biāo)題  也可以使用CATextLayer

@end

@implementation MKBar

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        
        
    }
    return self;
}
-(void)setTitleStr:(NSString *)titleStr
{
    _titleStr = titleStr;
    [self addSubview:self.titleLab];
    
    
    //CABasicAnimation *fade = [self fadeAnimation];
    //[self.textLayer addAnimation:fade forKey:nil];
    //[self.layer addSublayer:self.textLayer];
    
}

-(void)setDataArr:(NSMutableArray *)dataArr
{
    _dataArr = dataArr;
    
    self.barArr = [self barProgressArr:_dataArr];
    
    [self setProgress];
    
}
#pragma mark ---畫圖
-(void)setProgress
{
    __block float a = 0;
    //遍歷數(shù)組
    [self.barArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        //畫路徑
        UIBezierPath *beziPath = [UIBezierPath bezierPath];
        beziPath.lineWidth = 0.0;//線的寬度
        //起點(diǎn)坐標(biāo)
        
        [beziPath moveToPoint:CGPointMake(15,self.bounds.size.height-20)];
        //終點(diǎn)坐標(biāo)
        [beziPath addLineToPoint:CGPointMake(15,(MAX_TIME-self.totalNum)/MAX_TIME*(self.bounds.size.height-20))];
        beziPath.lineCapStyle = kCGLineCapRound;
        beziPath.lineJoinStyle = kCGLineJoinRound;
        [beziPath stroke];
        
        //畫圖
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        shapeLayer.fillColor = [UIColor clearColor].CGColor;
        shapeLayer.strokeColor = [obj[@"strokeColor"]CGColor];
        shapeLayer.lineWidth = 30.0;//寬度 目前是固定寬度 可以根據(jù)情況進(jìn)行修改
        shapeLayer.strokeStart = a;//起始點(diǎn)
        shapeLayer.strokeEnd = [obj[@"precent"] floatValue]+a;//結(jié)束點(diǎn)
        a = shapeLayer.strokeEnd;//從上一個(gè)起始點(diǎn)開始畫圖
        shapeLayer.path = beziPath.CGPath;//產(chǎn)生聯(lián)系
        
        [self.layer addSublayer:shapeLayer];
        
        
        //動(dòng)畫
        CABasicAnimation*pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        pathAnimation.duration=1.0f;
        pathAnimation.timingFunction= [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        pathAnimation.fromValue=@0.0f;
        pathAnimation.toValue=@(1);
        [shapeLayer addAnimation:pathAnimation forKey:@"strokeEndAnimation"];
        
        
    }];

    
    
}
#pragma mark ---處理進(jìn)度數(shù)據(jù)
-(NSMutableArray *)barProgressArr:(NSMutableArray *)dataArr
{
    NSMutableArray *barProgArr = [[NSMutableArray alloc]initWithCapacity:0];
    
    self.totalNum = 0.0;//總的時(shí)間
    float value = 0.0;//每一段時(shí)間
    NSString *boolStr;
    //計(jì)算總時(shí)間
    for (NSDictionary *dic in dataArr)
    {
        value = [dic[@"precent"] floatValue];
        
        self.totalNum = self.totalNum + value;
    }
    
    //計(jì)算進(jìn)度值
    for (NSDictionary *dic in dataArr)
    {
        value = [dic[@"precent"] floatValue];
        
        boolStr = dic[@"strokeColor"];
        
        NSMutableDictionary *progDic = [[NSMutableDictionary alloc]initWithCapacity:0];
        
        //根據(jù)BOOL確定顏色  當(dāng)然也可以添加多種顏色
        if ([boolStr isEqualToString:@"1"])
        {
            [progDic setObject:[UIColor redColor] forKey:@"strokeColor"];
        }
        else
        {
            [progDic setObject:RGB(83, 193, 124) forKey:@"strokeColor"];
        }
        
        //計(jì)算進(jìn)度 添加進(jìn)數(shù)組
        [progDic setObject:@(value/self.totalNum) forKey:@"precent"];
        
        [barProgArr addObject:progDic];
        
    }
    
    return barProgArr;
}
-(UILabel *)titleLab
{
    if (!_titleLab)
    {
        _titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, self.bounds.size.height-20, self.bounds.size.width, 20)];
        _titleLab.font = [UIFont systemFontOfSize:14.0];
        _titleLab.textAlignment = NSTextAlignmentCenter;
        _titleLab.textColor = [UIColor whiteColor];
        _titleLab.text = self.titleStr;
        
    }
    return _titleLab;
}
#pragma mark ---可以使用CATextLayer
-(CATextLayer*)textLayer
{
    if (!_textLayer) {
        _textLayer = [[CATextLayer alloc]init];
        _textLayer.string = self.titleStr;
        _textLayer.frame = CGRectMake(0, self.bounds.size.height-20, self.bounds.size.width, 20);
        [_textLayer setAlignmentMode:kCAAlignmentCenter];
        [_textLayer setForegroundColor:[[UIColor whiteColor] CGColor]];

        _textLayer.fontSize = 14.0;
    }
    
    return _textLayer;
}
//動(dòng)畫
-(CABasicAnimation*)fadeAnimation
{
    CABasicAnimation* fadeAnimation = nil;
    fadeAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeAnimation.fromValue = [NSNumber numberWithFloat:0.0];
    fadeAnimation.toValue = [NSNumber numberWithFloat:1.0];
    fadeAnimation.duration = 2.0;
    return fadeAnimation;
}

BarLayerView

BarLayerView.h

#import <UIKit/UIKit.h>

@interface BarLayerView : UIView


@property (nonatomic,strong)NSMutableArray *xArr;//X軸數(shù)據(jù)

@property (nonatomic,strong)NSMutableArray *dataArr;//進(jìn)度數(shù)據(jù)

@property (nonatomic,strong)NSMutableArray *barArr;//存放柱子的數(shù)組  用來刪除

-(void)strokeMKBarChart;//繪制

@end

BarLayerView.m

#import "BarLayerView.h"
#import "MKBar.h"

#define RGB(r,g,b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1]
@implementation BarLayerView


-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        self.barArr = [[NSMutableArray alloc]initWithCapacity:0];
        
        
    }
    return self;
}
-(void)setXArr:(NSMutableArray *)xArr
{
    _xArr = xArr;
}
-(void)setDataArr:(NSMutableArray *)dataArr
{
    _dataArr = dataArr;
}

-(void)strokeMKBarChart
{
    //刪除所有的柱子
    [self viewCleanupForCollection:self.barArr];
    [self upDateMKBarChart];
}
//繪圖
-(void)upDateMKBarChart
{
    
    CGFloat barInterval = (self.bounds.size.width-(30*(self.xArr.count+1)))/(self.xArr.count-1);
    
    for (int a = 0; a < self.xArr.count; a++)
    {
        
        MKBar *bar = [[MKBar alloc]initWithFrame:CGRectMake(10+(barInterval+30)*a, 0, 30, self.bounds.size.height)];
        bar.backgroundColor = RGB(54, 63, 86);
        [bar setDataArr:self.dataArr[a]];
        [bar setTitleStr:self.xArr[a]];
        
        [self.barArr addObject:bar];//添加進(jìn)數(shù)組中,重繪時(shí)刪除,重新創(chuàng)建
        
        [self addSubview:bar];
        
        
    }
    
    
}
//刪除所有的柱子
- (void)viewCleanupForCollection:(NSMutableArray *)array
{
    if (array.count) {
        [array makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [array removeAllObjects];
    }
}



ViewController

#import "ViewController.h"
#import "BarLayerView.h"
#import "MKBar.h"

#define RGB(r,g,b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1]
@interface ViewController ()

@property (nonatomic,strong)CAShapeLayer *shapeLayer;

@property (nonatomic,strong)BarLayerView *barLayerView;

@end


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //測(cè)試數(shù)據(jù)
    //單個(gè)柱子上的分段數(shù)據(jù)
    NSMutableArray *arr = [[NSMutableArray alloc]initWithCapacity:0];
    //需要展示幾段
    [arr addObject:@{@"precent":@"200",@"strokeColor":@"1"}];
    [arr addObject:@{@"precent":@"100",@"strokeColor":@"0"}];
    [arr addObject:@{@"precent":@"200",@"strokeColor":@"1"}];
    [arr addObject:@{@"precent":@"300",@"strokeColor":@"0"}];
    [arr addObject:@{@"precent":@"200",@"strokeColor":@"1"}];
    
    //柱子個(gè)數(shù)
    NSMutableArray *dataArr = [[NSMutableArray alloc]initWithCapacity:0];
    
    [dataArr addObject:arr];
    [dataArr addObject:arr];
    [dataArr addObject:arr];
    [dataArr addObject:arr];
    [dataArr addObject:arr];
    [dataArr addObject:arr];
    [dataArr addObject:arr];
    
    //X軸數(shù)據(jù)
    NSMutableArray *xArr = [[NSMutableArray alloc]initWithCapacity:0];
    [xArr addObject:@"1"];
    [xArr addObject:@"2"];
    [xArr addObject:@"3"];
    [xArr addObject:@"4"];
    [xArr addObject:@"5"];
    [xArr addObject:@"6"];
    [xArr addObject:@"7"];
    
    self.barLayerView = [[BarLayerView alloc]initWithFrame:CGRectMake(00, 100, self.view.bounds.size.width, 200)];
    
    self.barLayerView.backgroundColor = RGB(54, 63, 86);
    [self.barLayerView setDataArr:dataArr];//設(shè)置柱子進(jìn)度
    
    [self.barLayerView setXArr:xArr];//設(shè)置XLable
    
    [self.barLayerView strokeMKBarChart];//重繪
    
    [self.view addSubview:self.barLayerView];
    
}

當(dāng)然Demo也有許多需要更改的地方,比如固定的寬度等等

如果感覺對(duì)您有幫助,請(qǐng)順手點(diǎn)個(gè)贊,哈哈....

原創(chuàng)文章,如果轉(zhuǎn)載,請(qǐng)注明出處,謝謝.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末垛膝,一起剝皮案震驚了整個(gè)濱河市菇怀,隨后出現(xiàn)的幾起案子拒秘,更是在濱河造成了極大的恐慌知染,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,039評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件畸冲,死亡現(xiàn)場(chǎng)離奇詭異夜惭,居然都是意外死亡莹妒,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門舞吭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來泡垃,“玉大人,你說我怎么就攤上這事羡鸥∶镅ǎ” “怎么了?”我有些...
    開封第一講書人閱讀 165,417評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵惧浴,是天一觀的道長(zhǎng)存和。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么捐腿? 我笑而不...
    開封第一講書人閱讀 58,868評(píng)論 1 295
  • 正文 為了忘掉前任纵朋,我火速辦了婚禮,結(jié)果婚禮上叙量,老公的妹妹穿的比我還像新娘倡蝙。我一直安慰自己,他們只是感情好绞佩,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評(píng)論 6 392
  • 文/花漫 我一把揭開白布寺鸥。 她就那樣靜靜地躺著,像睡著了一般品山。 火紅的嫁衣襯著肌膚如雪胆建。 梳的紋絲不亂的頭發(fā)上赌结,一...
    開封第一講書人閱讀 51,692評(píng)論 1 305
  • 那天灰粮,我揣著相機(jī)與錄音,去河邊找鬼鳍征。 笑死涯呻,一個(gè)胖子當(dāng)著我的面吹牛凉驻,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播复罐,決...
    沈念sama閱讀 40,416評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼涝登,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了效诅?” 一聲冷哼從身側(cè)響起胀滚,我...
    開封第一講書人閱讀 39,326評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎乱投,沒想到半個(gè)月后咽笼,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,782評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡戚炫,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評(píng)論 3 337
  • 正文 我和宋清朗相戀三年剑刑,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片双肤。...
    茶點(diǎn)故事閱讀 40,102評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡叛甫,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出杨伙,到底是詐尸還是另有隱情其监,我是刑警寧澤,帶...
    沈念sama閱讀 35,790評(píng)論 5 346
  • 正文 年R本政府宣布限匣,位于F島的核電站抖苦,受9級(jí)特大地震影響毁菱,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜锌历,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 331
  • 文/蒙蒙 一贮庞、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧究西,春花似錦窗慎、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至扇丛,卻和暖如春术吗,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背帆精。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評(píng)論 1 272
  • 我被黑心中介騙來泰國打工较屿, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人卓练。 一個(gè)月前我還...
    沈念sama閱讀 48,332評(píng)論 3 373
  • 正文 我出身青樓隘蝎,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國和親襟企。 傳聞我的和親對(duì)象是個(gè)殘疾皇子末贾,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件整吆、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,105評(píng)論 4 62
  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一種新的協(xié)議。它實(shí)...
    香橙柚子閱讀 23,871評(píng)論 8 183
  • 魅力古城 來云南之前辉川,已經(jīng)聽許多人提起過麗江的美表蝙,此次云南之行也是因?yàn)閷?duì)麗江向往已久,想一堵它的芳容乓旗。 7月22日...
    英曼繪生活閱讀 297評(píng)論 0 1
  • 以下學(xué)習(xí)府蛇、摘錄自《非凡視覺:攝影大師的構(gòu)思與創(chuàng)作》 第3章 學(xué)會(huì)觀察 光亮逐漸驅(qū)走黑暗,原本模糊的天際線變得清晰屿愚,...
    whybask閱讀 197評(píng)論 0 0
  • 一朝一夕醉入懷 一晝一夜有十載 一詩一畫墨猶在 一世一生盼重來
    離凈閱讀 258評(píng)論 0 7