CorePlot 的高級用法-畫扇形圖和折線圖

![Uploading 屏幕快照 2017-04-24 下午4.58.32_334202.png . . .]
CorePlot的基礎(chǔ)學(xué)習(xí)可以去看這個CorePlot柱狀圖基礎(chǔ)學(xué)習(xí)

下面我們要做的視圖如下圖實(shí)例1和實(shí)例2所示(Demo傳送門):

扇形圖
折線圖
曲線圖
  • 實(shí)現(xiàn)扇形,并且實(shí)現(xiàn)每個扇形板塊的數(shù)據(jù),具體代碼如下:
#import "ViewController.h"
#import "CorePlot-CocoaTouch.h"

@interface ViewController ()<CPTPlotDataSource,CALayerDelegate>
@property (nonatomic, strong) NSMutableArray *arr;
@property (nonatomic, strong) CPTXYGraph *graph;
@property (nonatomic, strong) CPTPieChart *piePlot;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    // 創(chuàng)建畫布
    self.graph = [[CPTXYGraph alloc] initWithFrame:self.view.bounds];
    // 設(shè)置畫布主題
    CPTTheme *theme = [CPTTheme themeNamed:kCPTPlainWhiteTheme];
    [self.graph applyTheme:theme];
    // 畫布與周圍的距離
    self.graph.paddingTop = 10.0f;
    self.graph.paddingLeft = 5.0f;
    self.graph.paddingRight = 5.0f;
    self.graph.paddingBottom = 10.0f;
    // 將畫布的坐標(biāo)軸設(shè)置為空
    self.graph.axisSet = nil;
    
    // 創(chuàng)建畫板
    CPTGraphHostingView *hostView= [[CPTGraphHostingView alloc] initWithFrame:self.view.bounds];
    // 設(shè)置畫板的畫布
    hostView.hostedGraph =  self.graph;
    // 設(shè)置畫布標(biāo)題的風(fēng)格
    CPTMutableTextStyle *whiteText = [CPTMutableTextStyle textStyle];
    whiteText.color = [CPTColor blackColor];
    whiteText.fontName = @"Helvetica-Bold";
    whiteText.fontSize = 18.0;
    self.graph.titleTextStyle = whiteText;
    self.graph.title = @"餅狀圖";
    
    // 創(chuàng)建餅圖對象
    self.piePlot = [[CPTPieChart alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
    // 設(shè)置數(shù)據(jù)源
    self.piePlot.dataSource = self;
    // 設(shè)置餅狀圖半徑
    self.piePlot.pieRadius = 100.0;
    //設(shè)置餅圖表示符
    self.piePlot.identifier =@"pie chart";
    //餅圖開始繪制的位置
    self.piePlot.startAngle =M_PI_4;
    //餅圖繪制的方向(順時針/逆時針)
    self.piePlot.sliceDirection = CPTPieDirectionCounterClockwise;
    //餅圖的重心
    self.piePlot.centerAnchor =CGPointMake(0.5,0.38);
    //餅圖的線條風(fēng)格
    self.piePlot.borderLineStyle = [CPTLineStyle lineStyle];
    //設(shè)置代理
    self.piePlot.delegate =self;
    //將餅圖加到畫布上
    [self.graph addPlot:self.piePlot];
    
    //將畫板加到視圖上
    [self.view addSubview:hostView];
    
    //創(chuàng)建圖例
    CPTLegend *theLegeng = [CPTLegend legendWithGraph:self.graph];
    theLegeng.numberOfColumns =1;
    theLegeng.fill = [CPTFill fillWithColor:[CPTColor whiteColor]];
    theLegeng.borderLineStyle = [CPTLineStyle lineStyle];
    theLegeng.cornerRadius =5.0;
    theLegeng.delegate =self;
    
    self.graph.legend = theLegeng;
    self.graph.legendAnchor = CPTRectAnchorRight;
    self.graph.legendDisplacement =CGPointMake(-10,100);

}

//返回扇形數(shù)目
- (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
    return self.arr.count;
}
//返回每個扇形的比例
- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx {
    return [self.arr objectAtIndex:idx];
}

//凡返回每個扇形的標(biāo)題
- (CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)idx
{
    CPTTextLayer *label = [[CPTTextLayer alloc]initWithText:[NSString stringWithFormat:@"hello,%@",[self.arr objectAtIndex:idx]]];
    CPTMutableTextStyle *text = [label.textStyle mutableCopy];
    text.color = [CPTColor whiteColor];
    return label;
}

//選中某個扇形時的操作
- (void)pieChart:(CPTPieChart *)plot sliceWasSelectedAtRecordIndex:(NSUInteger)idx
{
    self.graph.title = [NSString stringWithFormat:@"比例:%@",[self.arr objectAtIndex:idx]];
}



//返回圖例
- (NSAttributedString *)attributedLegendTitleForPieChart:(CPTPieChart *)pieChart recordIndex:(NSUInteger)idx
{
    NSAttributedString *title = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"hi:%lu",(unsigned long)idx]];
    
    return title;
}

- (NSMutableArray *)arr {
    if (!_arr) {
        _arr = [NSMutableArray arrayWithObjects:@"1.0",@"3.0",@"1.0",@"2.0",@"2.0", nil];
    }
    return _arr;
}
  • 實(shí)現(xiàn)折線圖,并且實(shí)現(xiàn)折點(diǎn)顯示數(shù)據(jù),具體代碼如下:
#import "ViewController.h"
#import "CorePlot-CocoaTouch.h"
@interface ViewController ()<CPTPlotDataSource>
{
    NSMutableArray *_dataArray;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化數(shù)組, 并放入十個 0-20 間的隨機(jī)數(shù)
    _dataArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < 10; i++) {
        [_dataArray addObject:[NSNumber numberWithInt:rand()%20]];
    }
    
    CGRect frame = CGRectMake(20, 100, self.view.bounds.size.width - 40, 200);
    
    // 圖形要放在一個CPTGraphHostingView中, CPTGraphHostingView繼承 UIView的
    // 創(chuàng)建畫板
    CPTGraphHostingView *hostView = [[CPTGraphHostingView alloc] initWithFrame:frame];
    // 把CPTGraphHostingView 加在自己的view中
    [self.view addSubview:hostView];
    hostView.backgroundColor = [UIColor grayColor];
    
    // 在 CPTGraph 中畫圖, 這里的CPTXYGraph 是個曲線圖
    // 要指定CPTGraphHostingView 的hostteGraoh 屬性來關(guān)聯(lián)
    CPTXYGraph *graph = [[CPTXYGraph alloc] initWithFrame:hostView.frame];
    graph.identifier = @"test";
    hostView.hostedGraph = graph;
    
    // 設(shè)置曲線
    CPTScatterPlot *scatterPlot =[[CPTScatterPlot alloc] initWithFrame:graph.bounds];
    [graph addPlot:scatterPlot];
    scatterPlot.dataSource = self;//設(shè)定數(shù)據(jù)源,需應(yīng)用CPTPlotDataSource 協(xié)議
    
    // 設(shè)置PlotSpace,這里的 xRange 和 yRange 要理解好,它決定了點(diǎn)是否落在圖形的可見區(qū)域
    //location值表示坐標(biāo)起始值,一般可以設(shè)置元素中的最小值
    //length值表示從起始值上浮多少,一般可以用最大值減去最小值的結(jié)果
    
    CPTXYPlotSpace
    *plotSpace = (CPTXYPlotSpace *) scatterPlot.plotSpace;
    
    plotSpace.xRange= [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat([_dataArray count]-1)];
    
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat(20)];
    
    //  每個折點(diǎn)用圖片和文字展示具體數(shù)值  CPTTradingRangePlot
    /**
     CPTMutableLineStyle *whiteLineStyle = [CPTMutableLineStyle lineStyle]; whiteLineStyle.lineColor = [CPTColor whiteColor]; whiteLineStyle.lineWidth = 2.0;
     
     CPTTradingRangePlot *ohlcPlot = [[CPTTradingRangePlot alloc] initWithFrame:graph.bounds];
     
     ohlcPlot.identifier = @"OHLC";
     
     ohlcPlot.lineStyle = whiteLineStyle; //向上或向下的線條
     
     ohlcPlot.plotStyle = CPTTradingRangePlotStyleCandleStick;
     //ohlcPlot.shadow = whiteShadow;
     
     // ohlcPlot.labelShadow = whiteShadow;
     
     [graph addPlot:ohlcPlot];

     
     */
}
#pragma mark - CPTPlotDataSource
//詢問有多少個數(shù)據(jù)
- (NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
    return [_dataArray count];
}

// 詢問一個個數(shù)據(jù)值, 在CPTPlotDataSource中聲明的
- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx {
    if (fieldEnum == CPTScatterPlotFieldY) {  // 詢問 Y值時
        return [_dataArray objectAtIndex:idx];
    }else {
        return [NSNumber numberWithInt:(int)idx];
    }
}

// 返回每個折點(diǎn)的y軸  數(shù)據(jù)
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index {
    NSLog(@"%lu",(unsigned long)index);
    if (index == 0 || index == (_dataArray.count - 1)) {  // 去除 第一個  和最后一個 y軸數(shù)據(jù)
        CPTTextLayer *label = [[CPTTextLayer alloc]initWithText:@""];
        CPTMutableTextStyle *text = [ label.textStyle mutableCopy];
        text.color = [CPTColor whiteColor];
        return label;
    }else{
        CPTTextLayer *label = [[CPTTextLayer alloc]initWithText:[NSString stringWithFormat:@"%@",_dataArray[index]]];
        CPTMutableTextStyle *text = [ label.textStyle mutableCopy];
        text.color = [CPTColor whiteColor];
        return label;
    }
 }


繪制曲線圖,代碼如下:

#import "ViewController.h"
#import "CorePlot-CocoaTouch.h"

@interface ViewController ()<CPTPlotSpaceDelegate,CALayerDelegate,CPTPlotDataSource> {
    NSArray * _coordunatesX;
    NSArray * _coordunatesY;
}
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) CPTGraphHostingView *hostView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self config];
    // 加載數(shù)據(jù)
    [self initSetData];
    // 創(chuàng)建宿主HostView
    [self initSetupUI];
    // 創(chuàng)建圖表,用于顯示的畫布
    [self createGraph];
    //  創(chuàng)建繪圖空間
    [self createPlotSpace];
    // 創(chuàng)建坐標(biāo)
    [self createAxis];
    //創(chuàng)建平面圖,折線圖
    [self createPlots];
    // 創(chuàng)建圖例
    [self createLegend];
}

#pragma mark - 自定義方法
- (void)config {
    
}

- (void)initSetData {
    for (int i = 0; i < 10; i++) {
        [self.dataSource addObject:[NSNumber numberWithInt:arc4random() %10]];
    }
    
    _coordunatesX = @[@"第1次",@"第2次",@"第3次",@"第4次",@"第5次",@"第6次",@"第7次",@"第8次",@"第9次",@"第10次"];
    _coordunatesY = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10"];
}

#pragma mark - 創(chuàng)建宿主HostView
- (void)initSetupUI {
     //  圖形要放在CPTGraphHostingView宿主中,因?yàn)閁IView無法加載CPTGraph
    _hostView = [[CPTGraphHostingView alloc] initWithFrame:self.view.bounds];
    //  默認(rèn)值:NO,設(shè)置為YES可以減少GPU的使用,但是渲染圖形的時候會變慢
    _hostView.collapsesLayers = NO;
    //  允許捏合縮放 默認(rèn)值:YES
    _hostView.allowPinchScaling = NO;
    //  背景色 默認(rèn)值:clearColor
    _hostView.backgroundColor = [UIColor whiteColor];
    
    // 添加到View中
    [self.view addSubview:_hostView];
}

#pragma mark - 創(chuàng)建圖表,用于顯示的畫布
- (void)createGraph {
    // 基于xy軸的圖表創(chuàng)建
    CPTXYGraph *graph=[[CPTXYGraph alloc] initWithFrame:_hostView.bounds];
    // 使宿主視圖的hostedGraph與CPTGraph關(guān)聯(lián)
    _hostView.hostedGraph = graph;
    
    // 設(shè)置主題, 類似于 皮膚
    /**
     kCPTDarkGradientTheme、
     kCPTPlainBlackTheme、
     kCPTPlainWhiteTheme、
     kCPTSlateTheme、
     kCPTStocksTheme
     */
    CPTTheme *theme = [CPTTheme themeNamed:kCPTSlateTheme];
    [graph applyTheme:theme];
    
    // 標(biāo)題設(shè)置
    graph.title = @"標(biāo)題:曲線圖";
    // 標(biāo)題對齊于圖框的位置,可以用CPTRectAnchor枚舉類型,指定標(biāo)題向圖框的4角、4邊(中點(diǎn))對齊標(biāo)題位置 默認(rèn)值:CPTRectAnchorTop(頂部居中)
    graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
    // 標(biāo)題對齊時的偏移距離(相對于titlePlotAreaFrameAnchor的偏移距離)默認(rèn)值:CGPointZero
    graph.titleDisplacement = CGPointZero;
    // 標(biāo)題文本樣式 默認(rèn)值:nil
    CPTMutableTextStyle *textStyle = [[CPTMutableTextStyle alloc] init];
    textStyle.fontSize = CPTFloat(25);
    textStyle.textAlignment = CPTTextAlignmentLeft;
    graph.titleTextStyle = textStyle;
    
    // CPGGraph內(nèi)邊距,默認(rèn)值:20.0f
    graph.paddingLeft = CPTFloat(0);
    graph.paddingTop = CPTFloat(0);
    graph.paddingRight = CPTFloat(0);
    graph.paddingBottom = CPTFloat(0);
    
    // CPTPlotAreaFrame繪圖區(qū)域設(shè)置
    // 內(nèi)邊距設(shè)置,默認(rèn)值:0.0f
    graph.plotAreaFrame.paddingLeft = CPTFloat(0);
    graph.plotAreaFrame.paddingTop = CPTFloat(0);
    graph.plotAreaFrame.paddingRight = CPTFloat(0);
    graph.plotAreaFrame.paddingBottom = CPTFloat(0);
    // 邊框樣式設(shè)置 默認(rèn)值:nil
    graph.plotAreaFrame.borderLineStyle=nil;
}

#pragma mark - 創(chuàng)建繪圖空間
- (void)createPlotSpace {
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)_hostView.hostedGraph.defaultPlotSpace;
    // 繪圖空間是否允許與用戶交互 默認(rèn)值:NO
    plotSpace.allowsUserInteraction = YES;
    // 委托事件
    plotSpace.delegate = self;
    
    // 開啟用戶交互
     plotSpace.allowsUserInteraction = YES;
    
    // 可顯示大小 一屏內(nèi)橫軸/縱軸的顯示范圍
    // 橫軸
    // location表示坐標(biāo)的顯示起始值,length表示要顯示的長度 類似于NSRange
    CPTMutablePlotRange *xRange = [CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromCGFloat(-1) length:CPTDecimalFromCGFloat(_coordunatesX.count + 1)];
    // 橫軸顯示的收縮/擴(kuò)大范圍 1:不改變  <1:收縮范圍  >1:擴(kuò)大范圍
    [xRange expandRangeByFactor:CPTDecimalFromCGFloat(1)];
    
    plotSpace.xRange = xRange;
    
    // 縱軸
    CPTMutablePlotRange *yRange = [CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromCGFloat(-1) length:CPTDecimalFromCGFloat(11)];
    [yRange expandRangeByFactor:CPTDecimalFromCGFloat(1)];
    
    plotSpace.yRange = yRange;
    
    
    // 繪圖空間的最大顯示空間,滾動范圍
    CPTMutablePlotRange *xGlobalRange = [CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromCGFloat(-2) length:CPTDecimalFromCGFloat(_coordunatesX.count + 5)];
    
    CPTMutablePlotRange *yGlobalRange = [CPTMutablePlotRange plotRangeWithLocation:CPTDecimalFromCGFloat(-2) length:CPTDecimalFromCGFloat(16)];
    
    plotSpace.globalXRange = xGlobalRange;
    plotSpace.globalYRange = yGlobalRange;
    
}

#pragma mark - 創(chuàng)建坐標(biāo)
- (void)createAxis {
    // 軸線樣式
    CPTMutableLineStyle *axisLineStyle = [[CPTMutableLineStyle alloc] init];
    axisLineStyle.lineWidth = CPTFloat(1);
    axisLineStyle.lineColor = [CPTColor blackColor];
    
    // 標(biāo)題樣式
    CPTMutableTextStyle *titelStyle = [CPTMutableTextStyle textStyle];
    titelStyle.color = [CPTColor redColor];
    titelStyle.fontSize = CPTFloat(20);
    
    // 主刻度線樣式
    CPTMutableLineStyle *majorLineStyle = [CPTMutableLineStyle lineStyle];
    majorLineStyle.lineColor = [CPTColor purpleColor];
    
    // 細(xì)分刻度線樣式
    CPTMutableLineStyle *minorLineStyle = [CPTMutableLineStyle lineStyle];
    minorLineStyle.lineColor = [CPTColor blueColor];
    
    // 軸標(biāo)簽樣式
    CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init];
    axisTextStyle.color = [CPTColor blueColor];
    axisTextStyle.fontName = @"Helvetica-Bold";
    axisTextStyle.fontSize = CPTFloat(11);
    
    // 軸標(biāo)簽樣式
    CPTMutableTextStyle *axisLabelTextStyle = [[CPTMutableTextStyle alloc] init];
    axisLabelTextStyle.color=[CPTColor greenColor];
    axisLabelTextStyle.fontSize = CPTFloat(17);
    
    // 坐標(biāo)系
    CPTXYAxisSet *axis = (CPTXYAxisSet *)_hostView.hostedGraph.axisSet;
    
     //X軸設(shè)置
    
    // 獲取X軸線
    CPTXYAxis *xAxis = axis.xAxis;
    
    // 軸線設(shè)置
    xAxis.axisLineStyle = axisLineStyle;
    
    // 顯示的刻度范圍 默認(rèn)值:nil
    xAxis.visibleRange=[CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat(_coordunatesX.count - 1)];
    
     // 標(biāo)題設(shè)置
    xAxis.title =@ "X軸";
    // 文本樣式
    xAxis.titleTextStyle = titelStyle;
    // 位置 與刻度有關(guān),
    xAxis.titleLocation = CPTDecimalFromFloat(2);
    // 方向設(shè)置
    xAxis.tickDirection = CPTSignNegative;
    // 偏移量,在方向上的偏移量
    xAxis.titleOffset = CPTFloat(25);
    
     // 位置設(shè)置
    
    // 固定坐標(biāo) 默認(rèn)值:nil
    //xAxis.axisConstraints = [CPTConstraints constraintWithLowerOffset:50.0];
    // 坐標(biāo)原點(diǎn)所在位置,默認(rèn)值:CPTDecimalFromInteger(0)(在Y軸的0點(diǎn)位置)
    xAxis.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0);
    
    
    // 主刻度線設(shè)置
    // X軸大刻度線,線型設(shè)置
    xAxis.majorTickLineStyle = majorLineStyle;
    // 刻度線的長度
    xAxis.majorTickLength = CPTFloat(5);
    // 刻度線位置
    NSMutableSet *majorTickLocations =[NSMutableSet setWithCapacity:_coordunatesX.count];
    for (int i= 0 ;i< _coordunatesX.count ;i++) {
        [majorTickLocations addObject:[NSNumber numberWithInt:(i)]];
    }
    xAxis.majorTickLocations = majorTickLocations;
    
    // 細(xì)分刻度線設(shè)置
    // 刻度線的長度
    xAxis.minorTickLength = CPTFloat(3);
    // 刻度線樣式
    xAxis.minorTickLineStyle = minorLineStyle;
    // 刻度線位置
    NSInteger minorTicksPerInterval = 3;
    CGFloat minorIntervalLength = CPTFloat(1) / CPTFloat(minorTicksPerInterval + 1);
    NSMutableSet *minorTickLocations =[NSMutableSet setWithCapacity:(_coordunatesX.count - 1) * minorTicksPerInterval];
    for (int i= 0 ;i< _coordunatesX.count - 1;i++) {
        for (int j = 0; j < minorTicksPerInterval; j++) {
            [minorTickLocations addObject:[NSNumber numberWithFloat:(i + minorIntervalLength * (j + 1))]];
        }
    }
    xAxis.minorTickLocations = minorTickLocations;
    
    // 網(wǎng)格線設(shè)置
    //xAxis.majorGridLineStyle = majorLineStyle;
    //xAxis.minorGridLineStyle = minorLineStyle;
    //xAxis.gridLinesRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat(9)];
    
     // 軸標(biāo)簽設(shè)置
    //清除默認(rèn)的方案,使用自定義的軸標(biāo)簽、刻度線;
    xAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
    // 軸標(biāo)簽偏移量
    xAxis.labelOffset = 0.f;
    // 軸標(biāo)簽樣式
    xAxis.labelTextStyle = axisTextStyle;
    
    // 存放x軸自定義的軸標(biāo)簽
    NSMutableSet *xAxisLabels = [NSMutableSet setWithCapacity:_coordunatesX.count];
    for ( int i= 0 ;i< _coordunatesX.count ;i++) {
        CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:_coordunatesX[i] textStyle:axisLabelTextStyle];
        // 刻度線的位置
        newLabel.tickLocation = CPTDecimalFromInt(i);
        newLabel.offset = xAxis.labelOffset + xAxis.majorTickLength;
        newLabel.rotation = M_PI_4;
        [xAxisLabels addObject :newLabel];
    }
    xAxis.axisLabels = xAxisLabels;
    
     //Y軸設(shè)置
    // 獲取Y軸坐標(biāo)
    CPTXYAxis *yAxis = axis.yAxis;
    
    // 委托事件
    yAxis.delegate = self;
    
    //軸線樣式
    yAxis.axisLineStyle = axisLineStyle;
    
    //顯示的刻度
    yAxis.visibleRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromFloat(9)];
    
    // 存放x軸自定義的軸標(biāo)簽
    NSMutableSet *yAxisLabels = [NSMutableSet setWithCapacity:_coordunatesY.count];
    for ( int i= 0 ;i< _coordunatesY.count ;i++) {
        CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:_coordunatesY[i] textStyle:axisLabelTextStyle];
        // 刻度線的位置
        newLabel.tickLocation = CPTDecimalFromInt(i);
        newLabel.offset = yAxis.labelOffset + yAxis.majorTickLength;
        //newLabel.rotation = M_PI_4;
        [yAxisLabels addObject :newLabel];
    }
    yAxis.axisLabels = yAxisLabels;
    
    // 標(biāo)題設(shè)置
    
    yAxis.title = @"Y軸";
    // 文本樣式
    yAxis.titleTextStyle = titelStyle;
    // 位置 與刻度有關(guān),
    yAxis.titleLocation = CPTDecimalFromFloat(2.4);
    // 方向設(shè)置
    yAxis.tickDirection = CPTSignNegative;
    // 偏移量,在方向上的偏移量
    yAxis.titleOffset = CPTFloat(18);
    // 旋轉(zhuǎn)方向
    yAxis.titleRotation = CPTFloat(M_PI_2);
    
    // 位置設(shè)置
    // 獲取X軸原點(diǎn)即0點(diǎn)的坐標(biāo)
    CGPoint zeroPoint = [xAxis viewPointForCoordinateDecimalNumber:CPTDecimalFromFloat(0)];
    
    // 固定坐標(biāo) 默認(rèn)值:nil
    yAxis.axisConstraints = [CPTConstraints constraintWithLowerOffset:CPTFloat(zeroPoint.x)];
    
    // 坐標(biāo)原點(diǎn)所在位置,默認(rèn)值:CPTDecimalFromInteger(0)(在X軸的0點(diǎn)位置)
    //yAxis.orthogonalCoordinateDecimal = CPTDecimalFromFloat(0);
    
    
   // 主刻度線設(shè)置
    // 顯示數(shù)字標(biāo)簽的量度間隔
    yAxis.majorIntervalLength = CPTDecimalFromFloat(1);
    // 刻度線,線型設(shè)置
    yAxis.majorTickLineStyle = majorLineStyle;
    // 刻度線的長度
    yAxis.majorTickLength = 6;
    
    // 細(xì)分刻度線設(shè)置
    // 每一個主刻度范圍內(nèi)顯示細(xì)分刻度的個數(shù)
    yAxis.minorTicksPerInterval = 5;
    // 刻度線的長度
    yAxis.minorTickLength = CPTFloat(3);
    // 刻度線,線型設(shè)置
    yAxis.minorTickLineStyle = minorLineStyle;
    
    // 網(wǎng)格線設(shè)置 默認(rèn)不顯示
    yAxis.majorGridLineStyle = majorLineStyle;
    yAxis.minorGridLineStyle = minorLineStyle;
    yAxis.gridLinesRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromFloat(_coordunatesY.count)];
    
    // 軸標(biāo)簽設(shè)置
    // 軸標(biāo)簽偏移量
    yAxis.labelOffset = CPTFloat(5);
    // 軸標(biāo)簽樣式
    yAxis.labelTextStyle = axisTextStyle;
    
    // 排除不顯示的標(biāo)簽
    NSArray *exclusionRanges = [NSArray arrayWithObjects:
                                [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.99) length:CPTDecimalFromDouble(0.02)],
                                [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(2.99) length:CPTDecimalFromDouble(0.02)],
                                nil];
    yAxis.labelExclusionRanges = exclusionRanges;
    
    // 因?yàn)闆]有清除默認(rèn)的軸標(biāo)簽(CPTAxisLabelingPolicyNone),如果想要自定義軸標(biāo)簽,需實(shí)現(xiàn)委托方法
}

#pragma mark 創(chuàng)建平面圖,折線圖
- (void)createPlots{
    // 創(chuàng)建折線圖
    CPTScatterPlot *scatterPlot = [[CPTScatterPlot alloc] init];
    
    // 添加圖形到繪圖空間
    [_hostView.hostedGraph addPlot:scatterPlot];
    
    // 標(biāo)識,根據(jù)此@ref identifier來區(qū)分不同的plot,也是圖例顯示名稱,
    scatterPlot.identifier = @"scatter";
    
    // 設(shè)定數(shù)據(jù)源,需應(yīng)用CPTScatterPlotDataSource協(xié)議
    scatterPlot.dataSource = self;
    
    // 委托事件
    scatterPlot.delegate = self;
    
    // 線性顯示方式設(shè)置 默認(rèn)值:CPTScatterPlotInterpolationLinear(折線圖)
    // CPTScatterPlotInterpolationCurved(曲線圖)
    // CPTScatterPlotInterpolationStepped/CPTScatterPlotInterpolationHistogram(直方圖)
    scatterPlot.interpolation = CPTScatterPlotInterpolationCurved;
    
    
    // 數(shù)據(jù)標(biāo)簽設(shè)置,如果想用自定義的標(biāo)簽,則需要數(shù)據(jù)源方法:dataLabelForPlot:recordIndex:
    // 偏移量設(shè)置
    scatterPlot.labelOffset = 15;
    // 數(shù)據(jù)標(biāo)簽樣式
    CPTMutableTextStyle *labelTextStyle = [[CPTMutableTextStyle alloc] init];
    labelTextStyle.color = [CPTColor magentaColor];
    scatterPlot.labelTextStyle = labelTextStyle;
    
    
    // 線條樣式設(shè)置
    
    CPTMutableLineStyle * scatterLineStyle = [[ CPTMutableLineStyle alloc ] init];
    scatterLineStyle.lineColor = [CPTColor blackColor];
    scatterLineStyle.lineWidth = 3;
    // 破折線
    scatterLineStyle.dashPattern = @[@(10.0),@(5.0)];
    
    // 如果設(shè)置為nil則為散點(diǎn)圖
    scatterPlot.dataLineStyle = scatterLineStyle;
    
    // 添加拐點(diǎn)
    // 符號類型:橢圓
    CPTPlotSymbol *plotSymbol = [CPTPlotSymbol ellipsePlotSymbol];
    // 符號大小
    plotSymbol.size = CPTSizeMake(8.0f, 8.f);
    // 符號填充色
    plotSymbol.fill = [CPTFill fillWithColor:[CPTColor whiteColor]];
    // 邊框設(shè)置
    CPTMutableLineStyle *symboLineStyle = [[ CPTMutableLineStyle alloc ] init];
    symboLineStyle.lineColor = [CPTColor blackColor];
    symboLineStyle.lineWidth = 3;
    plotSymbol.lineStyle = symboLineStyle;
    
    // 向圖形上加入符號
    scatterPlot.plotSymbol = plotSymbol;
    
    // 設(shè)置拐點(diǎn)的外沿范圍,以用來擴(kuò)大檢測手指的觸摸范圍
    scatterPlot.plotSymbolMarginForHitDetection = CPTFloat(5);
    
    // 創(chuàng)建漸變區(qū)
    
    // 創(chuàng)建一個顏色漸變:從漸變色BeginningColor漸變到色endingColor
    CPTGradient *areaGradient = [CPTGradient gradientWithBeginningColor:[CPTColor blueColor] endingColor:[CPTColor clearColor]];
    // 漸變角度:-90 度(順時針旋轉(zhuǎn))
    areaGradient.angle = -90.0f ;
    // 創(chuàng)建一個顏色填充:以顏色漸變進(jìn)行填充
    CPTFill *areaGradientFill = [CPTFill fillWithGradient:areaGradient];
    // 為圖形設(shè)置漸變區(qū)
    scatterPlot.areaFill = areaGradientFill;
    // 漸變區(qū)起始值,小于這個值的圖形區(qū)域不再填充漸變色
    scatterPlot.areaBaseValue = CPTDecimalFromString (@"0.0" );
    
    // 顯示動畫
    scatterPlot.opacity = 0.0f;
    CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeInAnimation.duration            = 3.0f;
    fadeInAnimation.removedOnCompletion = NO;
    fadeInAnimation.fillMode            = kCAFillModeForwards;
    fadeInAnimation.toValue             = [NSNumber numberWithFloat:1.0];
    [scatterPlot addAnimation:fadeInAnimation forKey:@"animateOpacity"];
    
}

#pragma mark 創(chuàng)建圖例
- (void)createLegend
{
    // 圖例樣式設(shè)置
    NSMutableArray *plots = [NSMutableArray array];
    for (int i = 0; i < _hostView.hostedGraph.allPlots.count; i++) {
        CPTScatterPlot *scatterPlot = _hostView.hostedGraph.allPlots[i];
        
        CPTScatterPlot *plot = [[CPTScatterPlot alloc] init];
        plot.dataLineStyle = scatterPlot.dataLineStyle;
        plot.plotSymbol = scatterPlot.plotSymbol;
        plot.identifier = @"折線圖";
        [plots addObject:plot];
    }
    // 圖例初始化
    CPTLegend *legend = [CPTLegend legendWithPlots:plots];
    // 圖例的列數(shù)。有時圖例太多,單列顯示太長,可分為多列顯示
    legend.numberOfColumns = 1;
    // 圖例外框的線條樣式
    legend.borderLineStyle = nil;
    // 圖例的填充屬性,CPTFill 類型
    legend.fill = [CPTFill fillWithColor:[CPTColor clearColor]];
    // 圖例中每個樣本的大小
    legend.swatchSize = CGSizeMake(40, 10);
    // 圖例中每個樣本的文本樣式
    CPTMutableTextStyle *titleTextStyle = [CPTMutableTextStyle textStyle];
    titleTextStyle.color = [CPTColor blackColor];
    titleTextStyle.fontName = @"Helvetica-Bold";
    titleTextStyle.fontSize = 13;
    legend.textStyle = titleTextStyle;
    
    // 把圖例于圖表關(guān)聯(lián)起來
    _hostView.hostedGraph.legend = legend;
    // 圖例對齊于圖框的位置,可以用 CPTRectAnchor 枚舉類型,指定圖例向圖框的4角、4邊(中點(diǎn))對齊,默認(rèn)值:CPTRectAnchorBottom(底部居中)
    _hostView.hostedGraph.legendAnchor = CPTRectAnchorTopRight;
    // 圖例對齊時的偏移距離(相對于legendAnchor的偏移距離),默認(rèn)值:CGPointZeor
    _hostView.hostedGraph.legendDisplacement = CGPointMake(-10, 0);
}

#pragma mark 是否使用系統(tǒng)的軸標(biāo)簽樣式 并可改變標(biāo)簽樣式 可用于任何標(biāo)簽方案(labelingPolicy)
- (BOOL)axis:(CPTAxis *)axis shouldUpdateAxisLabelsAtLocations:(NSSet *)locations
{
    // 返回NO,使用自定義,返回YES,使用系統(tǒng)的標(biāo)簽
    return NO;
}

#pragma mark - CPTPlotSpace 代理
#pragma mark 替換移動坐標(biāo)
- (CGPoint)plotSpace:(CPTPlotSpace *)space willDisplaceBy:(CGPoint)proposedDisplacementVector
{
    //    NSLog(@"\n============willDisplaceBy==========\n");
    //    NSLog(@"原始的將要移動的坐標(biāo):%@", NSStringFromCGPoint(proposedDisplacementVector));
    //
    return proposedDisplacementVector;
}

#pragma mark 是否允許縮放
- (BOOL)plotSpace:(CPTPlotSpace *)space shouldScaleBy:(CGFloat)interactionScale aboutPoint:(CGPoint)interactionPoint
{
    //    NSLog(@"\n============shouldScaleBy==========\n");
    //    NSLog(@"縮放比例:%lf", interactionScale);
    //    NSLog(@"縮放的中心點(diǎn):%@", NSStringFromCGPoint(interactionPoint));
    return YES;  
}  

#pragma mark 縮放繪圖空間時調(diào)用,設(shè)置當(dāng)前顯示的大小
- (CPTPlotRange *)plotSpace:(CPTPlotSpace *)space willChangePlotRangeTo:(CPTPlotRange *)newRange forCoordinate:(CPTCoordinate)coordinate
{
    //    NSLog(@"\n============willChangePlotRangeTo==========\n");
    //    NSLog(@"坐標(biāo)類型:%d", coordinate);
    //    // CPTPlotRange 有比較方法 containsRange:
    //    NSLog(@"原始的坐標(biāo)空間:location:%@,length:%@", [NSDecimalNumber decimalNumberWithDecimal:newRange.location].stringValue, [NSDecimalNumber decimalNumberWithDecimal:newRange.length].stringValue);
    //
    return newRange;
}

#pragma mark 結(jié)束縮放繪圖空間時調(diào)用
- (void)plotSpace:(CPTPlotSpace *)space didChangePlotRangeForCoordinate:(CPTCoordinate)coordinate
{
    //    NSLog(@"\n============didChangePlotRangeForCoordinate==========\n");
    //    NSLog(@"坐標(biāo)類型:%d", coordinate);
}

#pragma mark 開始按下 point是在hostedGraph中的坐標(biāo)
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDownEvent:(CPTNativeEvent *)event atPoint:(CGPoint)point
{
    NSLog(@"\n\n\n============shouldHandlePointingDeviceDownEvent==========\n");
    NSLog(@"坐標(biāo)點(diǎn):%@", NSStringFromCGPoint(point));
    
    return YES;
}

#pragma mark 開始拖動 point是在hostedGraph中的坐標(biāo)
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDraggedEvent:(CPTNativeEvent *)event atPoint:(CGPoint)point
{
    NSLog(@"\n\n\n============shouldHandlePointingDeviceDraggedEvent==========\n");
    NSLog(@"坐標(biāo)點(diǎn):%@", NSStringFromCGPoint(point));
    
    return YES;
}

#pragma mark 松開 point是在hostedGraph中的坐標(biāo)
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceUpEvent:(CPTNativeEvent *)event atPoint:(CGPoint)point
{
    NSLog(@"\n\n\n============shouldHandlePointingDeviceUpEvent==========\n");
    NSLog(@"坐標(biāo)點(diǎn):%@", NSStringFromCGPoint(point));
    
    return YES;
}

#pragma mark 取消,如:來電時產(chǎn)生的取消事件
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceCancelledEvent:(CPTNativeEvent *)event
{
    NSLog(@"\n\n\n============shouldHandlePointingDeviceCancelledEvent==========\n");
    
    return YES;
}

#pragma mark - CPTScatterPlot的dataSource方法
#pragma mark 詢問有多少個數(shù)據(jù)
- (NSUInteger) numberOfRecordsForPlot:(CPTPlot *)plot {
    return self.dataSource.count;
}

#pragma mark 詢問一個個數(shù)據(jù)值 fieldEnum:一個軸類型,是一個枚舉  idx:坐標(biāo)軸索引
- (NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)idx
{
    NSNumber *num = nil;
    if(fieldEnum == CPTScatterPlotFieldY){            //詢問在Y軸上的值
        num = self.dataSource[idx];
    }else if (fieldEnum == CPTScatterPlotFieldX){     //詢問在X軸上的值
        num = @(idx);
    }
    return num;
}

#pragma mark 添加數(shù)據(jù)標(biāo)簽,在拐點(diǎn)上顯示的文本
- (CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)idx
{
    // 數(shù)據(jù)標(biāo)簽樣式
    CPTMutableTextStyle *labelTextStyle = [[CPTMutableTextStyle alloc] init];
    labelTextStyle.color = [CPTColor magentaColor];
    
    // 定義一個 TextLayer
    CPTTextLayer *newLayer = [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:@"%ld",(long)[self.dataSource[idx] integerValue]] style:labelTextStyle];
    
    return newLayer;
}

#pragma mark - CPTScatterPlot的delegate方法

- (void)scatterPlot:(CPTScatterPlot *)plot plotSymbolWasSelectedAtRecordIndex:(NSUInteger)idx withEvent:(UIEvent *)event
{
    // 移除注釋
    CPTPlotArea *plotArea = _hostView.hostedGraph.plotAreaFrame.plotArea;
    [plotArea removeAllAnnotations];
    
    // 創(chuàng)建拐點(diǎn)注釋,plotSpace:繪圖空間 anchorPlotPoint:坐標(biāo)點(diǎn)
    CPTPlotSpaceAnnotation *symbolTextAnnotation = [[CPTPlotSpaceAnnotation alloc] initWithPlotSpace:_hostView.hostedGraph.defaultPlotSpace anchorPlotPoint:@[@(idx),self.dataSource[idx]]];
    
    // 文本樣式
    CPTMutableTextStyle *annotationTextStyle = [CPTMutableTextStyle textStyle];
    annotationTextStyle.color = [CPTColor greenColor];
    annotationTextStyle.fontSize = 17.0f;
    annotationTextStyle.fontName = @"Helvetica-Bold";
    // 顯示的字符串
    NSString *randomValue = [NSString stringWithFormat:@"折線圖\n隨即值:%@ \n", [self.dataSource[idx] stringValue]];
    // 注釋內(nèi)容
    CPTTextLayer *textLayer = [[CPTTextLayer alloc] initWithText:randomValue style:annotationTextStyle];
    // 添加注釋內(nèi)容
    symbolTextAnnotation.contentLayer = textLayer;
    
    // 注釋位置
    symbolTextAnnotation.displacement = CGPointMake(CPTFloat(0), CPTFloat(20));
    
    // 把拐點(diǎn)注釋添加到繪圖區(qū)域中
    [plotArea addAnnotation:symbolTextAnnotation];
}



#pragma mark -  懶加載
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithCapacity:20];
    }
    return _dataSource;
}
@end

填坑,你集成好CorePolt庫后, 會出現(xiàn)類似

[CPTMutableNumericData setDataType:]: unrecognized selector sent to instance 0x1edcee60' 這樣的錯誤,因?yàn)樵谑褂渺o態(tài)庫時候會出現(xiàn)這種鏈接失效問題, 可以嘗試設(shè)置Link Flag 為 -all_load -Objc即可.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,754評論 4 61
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,361評論 25 708
  • 我是紫君 我的原創(chuàng) 6月2日,江蘇揚(yáng)州,隨著2017年高考臨近,揚(yáng)州市蔣王中學(xué)為每位備戰(zhàn)高考的高三學(xué)生,發(fā)放了兩張...
    昭潔紫君閱讀 447評論 0 0
  • 和家人共同成長,和愛人共同成長。和朋友共同成長。和同事共同成長。 為什么要共同成長呢?首先看到別人做到,自己也想要...
    親愛的吳小仙閱讀 290評論 0 1
  • 看慣了秋月春風(fēng),才知道什么樣的東西是美的,所以我認(rèn)為人生的階段就是爬山。 境界低,很多人爬到了山腳,不愿爬,看到的...
    山南有竹閱讀 305評論 0 0

友情鏈接更多精彩內(nèi)容