iOS 는 차 트 프레임 으로 기둥 그림 그리 기

우선 최종 적 으로 실현 해 야 할 효 과 를 살 펴 보 자.

최종 효과
1.barChartView 초기 화
기둥 그림 을 그 리 려 면 BarChartView 와 같은 종류 가 필요 합 니 다.다음은 초기 화 코드 입 니 다.

self.barChartView = [[BarChartView alloc] init];
self.barChartView.delegate = self;//    
[self.view addSubview:self.barChartView];
[self.barChartView mas_makeConstraints:^(MASConstraintMaker *make) {
 make.size.mas_equalTo(CGSizeMake(self.view.bounds.size.width-20, 300));
 make.center.mas_equalTo(self.view);
}];
2.barChartView 의 외관 스타일 설정
1.기본 스타일

self.barChartView.backgroundColor = [UIColor colorWithRed:230/255.0f green:253/255.0f blue:253/255.0f alpha:1];
self.barChartView.noDataText = @"    ";//          
self.barChartView.drawValueAboveBarEnabled = YES;//              
self.barChartView.drawHighlightArrowEnabled = NO;//           
self.barChartView.drawBarShadowEnabled = NO;//           
2.barChartView 의 상호작용 설정

self.barChartView.scaleYEnabled = NO;//  Y   
self.barChartView.doubleTapToZoomEnabled = NO;//      
self.barChartView.dragEnabled = YES;//      
self.barChartView.dragDecelerationEnabled = YES;//          
self.barChartView.dragDecelerationFrictionCoef = 0.9;//            (0~1),    ,      
3.barChartView 의 X 축 스타일 설정
먼저 barChartView 의 X 축 을 가 져 와 설정 해 야 합 니 다.
barChartView 의 xAxis 속성 을 통 해 X 축 을 얻 을 수 있 습 니 다.코드 는 다음 과 같 습 니 다.hartXAxis *xAxis = self.barChartView.xAxis;X 축 스타일 의 코드 를 다음 과 같이 설정 합 니 다.

ChartXAxis *xAxis = self.barChartView.xAxis;
xAxis.axisLineWidth = 1;//  X   
xAxis.labelPosition = XAxisLabelPositionBottom;//X      ,         
xAxis.drawGridLinesEnabled = NO;//      
xAxis.spaceBetweenLabels = 4;//  label  ,    1,        ,           label
xAxis.labelTextColor = [UIColor brownColor];//label    
4.barChartView 의 Y 축 스타일 설정
barChartView 기본 스타일 에 좌우 양쪽 Y 축 이 그 려 집 니 다.먼저 오른쪽 Y 축 을 숨겨 야 합 니 다.코드 는 다음 과 같 습 니 다.self.barChartView.rightAxis.enabled = NO;// 이어서 왼쪽 Y 축의 스타일 을 설정 합 니 다.
먼저 Y 축 축선 의 스타일 을 설정 합 니 다.코드 는 다음 과 같 습 니 다.

leftAxis.forceLabelsEnabled = NO;//          label
leftAxis.showOnlyMinMaxEnabled = NO;//            
leftAxis.axisMinValue = 0;//  Y     
leftAxis.startAtZeroEnabled = YES;// 0    
leftAxis.axisMaxValue = 105;//  Y     
leftAxis.inverted = NO;//   Y       
leftAxis.axisLineWidth = 0.5;//Y   
leftAxis.axisLineColor = [UIColor blackColor];//Y   
labelCount 속성 을 통 해 Y 축 을 균등 하 게 나 눌 수 있 는 수량 을 설정 합 니 다.
여기 서 설명 하 자 면,설 정 된 labelCount 의 값 은 반드시 Y 축 이 균등 하 게 나 눌 수 있 는 수량 이 아 닙 니 다.이것 은 forceLabelsEnabled 속성 에 달 려 있 습 니 다.forceLabelsEnabled 가 YES 와 같 으 면 지 정 된 수량의 label 을 강제로 그립 니 다.그러나 균등 하 게 나 눌 수 없습니다.코드 는 다음 과 같 습 니 다.

ChartYAxis *leftAxis = self.barChartView.leftAxis;//    Y 
leftAxis.labelCount = 5;
leftAxis.forceLabelsEnabled = NO;
Y 축 에 있 는 태그 의 스타일 을 설정 합 니 다.코드 는 다음 과 같 습 니 다.

leftAxis.labelPosition = YAxisLabelPositionOutsideChart;//label   
leftAxis.labelTextColor = [UIColor brownColor];//    
leftAxis.labelFont = [UIFont systemFontOfSize:10.0f];//    
Y 축 에 표 시 된 숫자 형식 을 설정 합 니 다.코드 는 다음 과 같 습 니 다.

leftAxis.valueFormatter = [[NSNumberFormatter alloc] init];//     
leftAxis.valueFormatter.positiveSuffix = @" $";//      
Y 축 인터넷 격자 선 스타일 을 설정 합 니 다.코드 는 다음 과 같 습 니 다.

leftAxis.gridLineDashLengths = @[@3.0f, @3.0f];//          
leftAxis.gridColor = [UIColor colorWithRed:200/255.0f green:200/255.0f blue:200/255.0f alpha:1];//     
leftAxis.gridAntialiasEnabled = YES;//     
Y 축 에 제한 선 을 추가 합 니 다.코드 는 다음 과 같 습 니 다.

ChartLimitLine *limitLine = [[ChartLimitLine alloc] initWithLimit:80 label:@"   "];
limitLine.lineWidth = 2;
limitLine.lineColor = [UIColor greenColor];
limitLine.lineDashLengths = @[@5.0f, @5.0f];//    
limitLine.labelPosition = ChartLimitLabelPositionRightTop;//  
[leftAxis addLimitLine:limitLine];//   Y  
leftAxis.drawLimitLinesBehindDataEnabled = YES;//              
5.barChartView 의 다른 스타일 설정
legend 를 통 해 그림 의 대상 을 가 져 온 다음 숨 깁 니 다.코드 는 다음 과 같 습 니 다.self.barChartView.legend.enabled = NO;// 설명 문 자 를 숨 깁 니 다.코드 는 다음 과 같 습 니 다.self.barChartView.descriptionText = @"";// , 3.barChartView 의 데이터 제공
barChartView 에 데 이 터 를 제공 하 는 것 은 data 속성 을 통 해 제 공 된 것 입 니 다.먼저 BarChartData 데이터 대상 을 만들어 야 합 니 다.코드 는 다음 과 같 습 니 다.

//        
- (BarChartData *)setData{
 int xVals_count = 12;//X          
 double maxYVal = 100;//Y     
 //X          
 NSMutableArray *xVals = [[NSMutableArray alloc] init];
 for (int i = 0; i < xVals_count; i++) {
 [xVals addObject:[NSString stringWithFormat:@"%d ", i+1]];
 }
 //  Y          
 NSMutableArray *yVals = [[NSMutableArray alloc] init];
 for (int i = 0; i < xVals_count; i++) {
 double mult = maxYVal + 1;
 double val = (double)(arc4random_uniform(mult));
 BarChartDataEntry *entry = [[BarChartDataEntry alloc] initWithValue:val xIndex:i];
 [yVals addObject:entry];
 }
 //  BarChartDataSet  ,     Y     ,          
 BarChartDataSet *set1 = [[BarChartDataSet alloc] initWithYVals:yVals label:nil];
 set1.barSpace = 0.2;//            (  +  )   
 set1.drawValuesEnabled = YES;//            
 set1.highlightEnabled = NO;//              ,(         )
 [set1 setColors:ChartColorTemplates.material];//       
 // BarChartDataSet       
 NSMutableArray *dataSets = [[NSMutableArray alloc] init];
 [dataSets addObject:set1];
 //  BarChartData  ,      barChartView        
 BarChartData *data = [[BarChartData alloc] initWithXVals:xVals dataSets:dataSets];
 [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:10.f]];//    
 [data setValueTextColor:[UIColor orangeColor]];//    
 NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
 //         
 [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
 [formatter setPositiveFormat:@"#0.0"];
 [data setValueFormatter:formatter];
 return data;
}
barChartView 에 데 이 터 를 제공 하고 애니메이션 효 과 를 설정 합 니 다.코드 는 다음 과 같 습 니 다.

self.data = [self setData];
 //        
 self.barChartView.data = self.data;
//      ,    X  Y      
[self.barChartView animateWithYAxisDuration:1.0f];
4.barChartView 를 실현 하 는 대리 방법
1.기둥 그림 을 선택 한 프 록 시 방법 을 누 르 십시오.코드 는 다음 과 같 습 니 다.

- (void)chartValueSelected:(ChartViewBase * _Nonnull)chartView entry:(ChartDataEntry * _Nonnull)entry dataSetIndex:(NSInteger)dataSetIndex highlight:(ChartHighlight * _Nonnull)highlight{
 NSLog(@"---chartValueSelected---value: %g", entry.value);
}
2.기둥 그림 을 선택 한 프 록 시 방법 이 없습니다.코드 는 다음 과 같 습 니 다.

- (void)chartValueNothingSelected:(ChartViewBase * _Nonnull)chartView{
 NSLog(@"---chartValueNothingSelected---");
}
기둥 그림 을 선택 한 후 공백 에서 두 번 클릭 하면 선택 을 취소 할 수 있 습 니 다.이 방법 을 되 돌려 줍 니 다.
3.기둥 그림 을 확대 하거나 축소 할 때의 대리 방법,코드 는 다음 과 같다.

- (void)chartScaled:(ChartViewBase * _Nonnull)chartView scaleX:(CGFloat)scaleX scaleY:(CGFloat)scaleY{
 NSLog(@"---chartScaled---scaleX:%g, scaleY:%g", scaleX, scaleY);
}
4.그래프 를 끌 어 당 길 때의 프 록 시 방법

- (void)chartTranslated:(ChartViewBase * _Nonnull)chartView dX:(CGFloat)dX dY:(CGFloat)dY{
 NSLog(@"---chartTranslated---dX:%g, dY:%g", dX, dY);
}
실행 결 과 는 다음 과 같 습 니 다.

실행 결과
데모 다운로드 주소:http://xiazai.jb51.net/201612/yuanma/BarChartDemo-BarChartDemo_jb51.rar
이상 은 본 고의 모든 내용 입 니 다.본 고의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 도움 이 되 기 를 바 랍 니 다.또한 저 희 를 많이 지지 해 주시 기 바 랍 니 다!

좋은 웹페이지 즐겨찾기