1. How to add Charts to my own project; 2. Select one during initialization. 3. Output the label when the pie chart is selected to identify the pie chart. 4. Change the text in the middle of the pie chart. 5. Remove the gap in the pie chart; 6. Remove a circle of light block mask at the hollow part of the pie chart;

Preface: Pie charts are particularly important in data statistics, but it is not a good method to draw them directly. They need to use the knowledge related to Sell curve, CAAnimation and CAShapLayer in Core Animation. In most cases, they need to calculate angles and so on. Fortunately there is a framework called Charts can help us to simplify this step, only need a simple integration can draw beautiful pie chart, but when using this framework will still exist many problems, because the version of the Charts is Swift, bridge, the properties of it is various, don’t know so fast you need to complete the property, The following blogger explains how to use the PieChartView for problems encountered during development.

1. How to add Charts to my own project; There are two ways to import Charts into your own project, one is through POD import, the other is to directly import project files. Pod version 3.0.4 is currently introduced as:

    pod 'Charts'
Copy the code

If you can’t use POD, go to the blogger category to find the installation method.

It is also not difficult to import project files. Directly import the “Charts” project files, the blue one, because it is Swift, Swift support needs to be set, currently 4.0. It is also necessary to introduce Chart FRmework in general-Linked FreameWorks and Libraries. The specific methods are available on our own baidu. There are too many on the Internet.

The easiest way to create a Swift file is to create a Swift file in oc. It will prompt you to create a bridge street file.

@import Charts;
Copy the code

If you are not prompted to create a bridge file, look for it in the blogger Swift category, not paraphrase.

2. Select one during initialization. We want the pie chart to be highlighted by the time we enter this interface, and the pie chart needs to be initialized before we can do that. I recommend a blog post that is well written and clearly annotated: PieCharView initialization and detailed annotation.

After reading this post, let’s go on to see how to set the highlight state:

/ / the meaning of this code is to set up the zeroth to highlight state, and does not cancel the agent, the X you can simply ignored, y represent your specific to the value of a piece of the pie chart, why want to ignore X, because print is 0, to be honest bloggers also didn't clear where the X role, in short it will not affect the whole program, have know, You can comment below. Thank you. In addition, this code is written after the completion of Chart initialization, usually there will be an animation, this is set according to their own needs, completely controllable. [_chartView highlightValueWithX:maxIndex dataSetIndex:0]; // As you can see above, the blogger communicated with members of the Charts team to make sure they didn't write the public method PIeChart chose, so looked at the source code for themselves and found it was also amazing that it could be done. Interested can look at our chat record: https://github.com/danielgindi/Charts/issues/3110 which is a maxIndex, corresponding to join the order of the array. PieChart does not have a public default selection method. The author's idea is to implement the default selection method himself, but the above method is feasible for bloggers.Copy the code

[self.chartView highlightValueWithX:0.0f y:762140.00 dataSetIndex:0 callDelegate:NO]; I’m going to show you where index came from, but I’m going to keep going.

3. Output the label when the pie chart is selected to identify the pie chart. ChartView has four proxy methods, we use two, one selected, one unselected:

- (void)chartValueSelected:(ChartViewBase * __nonnull)chartView entry:(ChartDataEntry * __nonnull)entry highlight:(ChartHighlight * __nonnull)highlight

- (void)chartValueNothingSelected:(ChartViewBase * __nonnull)chartView
Copy the code

Prints the current label when selected:

- (void)chartValueSelected:(ChartViewBase * __nonnull)chartView entry:(ChartDataEntry * __nonnull)entry highlight:(ChartHighlight * __nonnull)highlight { NSLog(@"chartValueSelected"); // NSLog(@"-- chartValueSelected-- value: %g", entry.y); // NSLog(@"-- chartValueSelected-- value: %g", entry.y); // Index NSLog(@"-- chartValueSelected-- value: %@", entry.data); // Index NSLog(@"-- chartValueSelected-- value: %@", entry. } /* The index of the pie chart is not needed. The index of the pie chart is not needed. What if there are pie charts that have exactly the same percentage? Can't tell, which is why the blogger later abandoned this method to determine the number; 2. If you print entry. Data when everything is fine, you'll be disappointed. * /Copy the code

Set the “index” of the pie chart

// Give your pie chart a value in data, pretend it is a tag, and rest assured that the blogger will eventually give you a complete initialization method, don't panic now. [values addObject:[[PieChartDataEntry alloc] initWithValue:762140.00 Label :nil Data :@"0"]]; [values addObject:[[PieChartDataEntry alloc] initWithValue:786600.00 label:nil data:@"1"]]; [values addObject:[[PieChartDataEntry alloc] initWithValue:160000.00 Label :nil Data :@"2"]]; [values addObject:[[PieChartDataEntry alloc] initWithValue:786600.00 label:nil data:@"3"]]; [values addObject:[[PieChartDataEntry alloc] initWithValue:786600.00 label:nil data:@"4"]]; [values addObject:[[PieChartDataEntry alloc] initWithValue:786600.00 label:nil data:@"5"]];Copy the code

At this point, you can distinguish which piece is completed and which piece is taken. You can change the text in the center when selecting the piece, or do other things, see ⬇️ below

4. Change the text in the middle of the pie chart. First look at the selected proxy method:

- (void)chartValueSelected:(ChartViewBase * __nonnull)chartView entry:(ChartDataEntry * __nonnull)entry highlight:(ChartHighlight * __nonnull)highlight { NSLog(@"chartValueSelected"); NSArray *titleArray = @[@"x",@"xx",@"xxx"]; NSArray *tmpArray; if (_circlePartArray) { tmpArray = _circlePartArray; } else {tmpArray = @[@762140.00,@786600.00,@11134.00]; } NSLog(@"---chartValueSelected---value: %g", entry.y); NSLog(@"---chartValueSelected---value: %@", entry.data); // The following method is used to set the text in the center of the pie chart, which also happens to use rich text. Or the commonly used NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail; paragraphStyle.alignment = NSTextAlignmentCenter; NSString *contentStr = [NSString stringWithFormat:@"%@\n%.2f",titleArray[[entry.data intValue]],[tmpArray[[entry.data intValue]] floatValue]]; NSMutableAttributedString *centerText = [[NSMutableAttributedString alloc] initWithString:contentStr]; [centerText setAttributes:@{ NSFontAttributeName: [UIFont PFSCRegularFontWithSize:12.f], NSParagraphStyleAttributeName: paragraphStyle } range:NSMakeRange(0, centerText.length)]; [centerText addAttributes:@{ NSFontAttributeName: [UIFont PFSCRegularFontWithSize:12.f], NSForegroundColorAttributeName: UIColor.gray9 } range:NSMakeRange(0, [titleArray[[entry.data intValue]] length])]; [centerText addAttributes:@{ NSFontAttributeName: [UIFont AsapMeidumFontWithSize:14.f], NSForegroundColorAttributeName: [UIColor gray3] } range:NSMakeRange([titleArray[[entry.data intValue]] length], centerText.length - [titleArray[[entry.data intValue]] length])]; _chartView.centerAttributedText = centerText; }Copy the code

The above logical, should not have what objection, because get the current index, so change its value completely not at all, that blogger long continue to say ⬇️

5. Remove the gap in the pie chart; When you initialize the pie chart, you can see that there are several pixels between the pie charts. Because there are many chartView attributes, you still need to be patient to find them.

dataSet.sliceSpace = 0;
Copy the code

This is the property of the PieChartDataSet.

6. Remove a circle of light block mask at the hollow part of the pie chart; The pie chart that we see has a hole in the middle, a mask, so that your pie chart is not solid color, if the product, the test raises this problem, or the design itself is solid color, you have to remove it, how do you remove it? If you are not familiar with Swift, it may be difficult to find oh, look at the following code:

// The following lines of code are the key, according to the comment can be clear to know how to do, should not be the blogger again blah blah blah, try to set yourself. _pieChartView.drawHoleEnabled = YES; . / / whether the pie chart is hollow _pieChartView holeRadiusPercent = 0.5; HoleColor = [UIColor clearColor]; // holeColor = [UIColor clearColor]; / / hollow color _pieChartView. TransparentCircleRadiusPercent = 0.52; . / / hollow translucent radius of _pieChartView transparentCircleColor = [UIColor colorWithRed: 210/255.0 green: 145/255.0 blue: 165/255.0 Alpha: 0.3]; // Translucent hollow colorCopy the code

The above are the problems encountered by the blogger when using the pie Charts in the Charts. Some of the answers may not be found on the Internet, which are also figured out by the blogger himself. Welcome to supplement.

//想要看效果的话就集成一下试试看吧,去掉博主里的数据,加一个属性就可以直接运行
#import "LCCircleView.h"
@implementation LCCircleView
{
    NSArray *parties;
    NSArray *circlePercentArray;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self creatCircleView];
    }
    return self;
}

- (void)creatCircleView
{
    _chartView = [[PieChartView alloc]init];
    [self addSubview:_chartView];
    [self setupPieChartView:_chartView];
    _chartView.layout.x(0).y(0).rightValue(0).base(0);
    _chartView.transparentCircleColor = [UIColor clearColor];
    _chartView.delegate = self;
    //图示
    ChartLegend *l = _chartView.legend;
    l.horizontalAlignment = ChartLegendHorizontalAlignmentRight;
    l.verticalAlignment = ChartLegendVerticalAlignmentTop;
    l.orientation = ChartLegendOrientationVertical;
    l.drawInside = NO;
    l.xEntrySpace = 0.0;
    l.yEntrySpace = 0.0;
    l.yOffset = 0.0;
    l.formSize = 0;

    // entry label styling
    _chartView.entryLabelColor = UIColor.whiteColor;
    _chartView.entryLabelFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:12.f];
    [self setDataCount:4 range:100.f];
    [self.chartView highlightValueWithX:0.0f y:762140.00 dataSetIndex:0 callDelegate:NO];

    [_chartView animateWithXAxisDuration:1.4 easingOption:ChartEasingOptionEaseOutBack];

}

- (void)setCirclePartArray:(NSArray *)circlePartArray
{
    _circlePartArray = circlePartArray;

    [self setDataCount:4 range:100.f];

    [_chartView animateWithXAxisDuration:1.4 easingOption:ChartEasingOptionEaseOutBack];

    if ([_circlePartArray[0] floatValue] > 0) {
    //这里已经修改了选中的方法
        [_chartView highlightValueWithX:maxIndex dataSetIndex:0];
    }


}

- (void)setDataCount:(int)count range:(double)range
{

    NSMutableArray *values = [[NSMutableArray alloc] init];
    PieChartDataSet *dataSet;
    if (_circlePartArray) {
        for (int i = 0; i < _circlePartArray.count; i++) {
            [values addObject:[[PieChartDataEntry alloc] initWithValue:[_circlePartArray[i] floatValue] label:nil data:[NSString stringWithFormat:@"%d",i]]];
        }
        dataSet = [[PieChartDataSet alloc] initWithValues:values label:nil];
        //
        dataSet.drawIconsEnabled = NO;
        dataSet.sliceSpace = 0.0;
        dataSet.iconsOffset = CGPointMake(0, 40);
        // add a lot of colors

        NSArray *pointColors = @[[UIColor colorWithRGB:@"#FD615E"],
                                 [UIColor colorWithRGB:@"#43BF97"],
                                 [UIColor colorWithRGB:@"#FFB92F"],
                                 [UIColor colorWithRGB:@"#4D7DFE"],
                                 [UIColor colorWithRGB:@"#BC99FF"],
                                 [UIColor colorWithRGB:@"#8180FF"]];

        dataSet.colors = pointColors;

        [self setupPieChartView:_chartView];


    }
    else
    {
        [values addObject:[[PieChartDataEntry alloc] initWithValue:762140.00 label:nil data:@"0"]];
        [values addObject:[[PieChartDataEntry alloc] initWithValue:786600.00 label:nil data:@"1"]];
        [values addObject:[[PieChartDataEntry alloc] initWithValue:160000.00 label:nil data:@"2"]];
        [values addObject:[[PieChartDataEntry alloc] initWithValue:786600.00 label:nil data:@"3"]];
        [values addObject:[[PieChartDataEntry alloc] initWithValue:786600.00 label:nil data:@"4"]];
        [values addObject:[[PieChartDataEntry alloc] initWithValue:786600.00 label:nil data:@"5"]];

        dataSet = [[PieChartDataSet alloc] initWithValues:values label:nil];
        dataSet.drawIconsEnabled = NO;
        dataSet.sliceSpace = 0.0;
        dataSet.iconsOffset = CGPointMake(0, 40);
        // add a lot of colors

        NSArray *pointColors = @[[UIColor colorWithRGB:@"#FD615E"],
                                 [UIColor colorWithRGB:@"#43BF97"],
                                 [UIColor colorWithRGB:@"#FFB92F"],
                                 [UIColor colorWithRGB:@"#4D7DFE"],
                                 [UIColor colorWithRGB:@"#BC99FF"],
                                 [UIColor colorWithRGB:@"#8180FF"]];

        dataSet.colors = pointColors;

    }





    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];

    NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];
    pFormatter.numberStyle = NSNumberFormatterPercentStyle;
    pFormatter.maximumFractionDigits = 1;
    pFormatter.multiplier = @1.f;
    pFormatter.percentSymbol = @" %";
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:pFormatter]];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:11.f]];
    [data setValueTextColor:UIColor.clearColor];

    _chartView.data = data;

}

- (void)optionTapped:(NSString *)key
{
    if ([key isEqualToString:@"toggleXValues"])
    {
        _chartView.drawSliceTextEnabled = !_chartView.isDrawSliceTextEnabled;

        [_chartView setNeedsDisplay];
        return;
    }

    if ([key isEqualToString:@"togglePercent"])
    {
        _chartView.usePercentValuesEnabled = !_chartView.isUsePercentValuesEnabled;

        [_chartView setNeedsDisplay];
        return;
    }

    if ([key isEqualToString:@"toggleHole"])
    {
        _chartView.drawHoleEnabled = !_chartView.isDrawHoleEnabled;

        [_chartView setNeedsDisplay];
        return;
    }

    if ([key isEqualToString:@"drawCenter"])
    {
        _chartView.drawCenterTextEnabled = !_chartView.isDrawCenterTextEnabled;

        [_chartView setNeedsDisplay];
        return;
    }

    if ([key isEqualToString:@"animateX"])
    {
        [_chartView animateWithXAxisDuration:1.4];
        return;
    }

    if ([key isEqualToString:@"animateY"])
    {
        [_chartView animateWithYAxisDuration:1.4];
        return;
    }

    if ([key isEqualToString:@"animateXY"])
    {
        [_chartView animateWithXAxisDuration:1.4 yAxisDuration:1.4];
        return;
    }

    if ([key isEqualToString:@"spin"])
    {
        [_chartView spinWithDuration:2.0 fromAngle:_chartView.rotationAngle toAngle:_chartView.rotationAngle + 360.f easingOption:ChartEasingOptionEaseInCubic];
        return;
    }

//    [super handleOption:key forChartView:_chartView];
}


#pragma mark - ChartViewDelegate

- (void)chartValueSelected:(ChartViewBase * __nonnull)chartView entry:(ChartDataEntry * __nonnull)entry highlight:(ChartHighlight * __nonnull)highlight
{
    NSLog(@"chartValueSelected");
    NSArray *titleArray = @[@"1",@"2",@"3",@"4",@"5",@"6"];
    NSArray *tmpArray;
    if (_circlePartArray) {
        tmpArray = _circlePartArray;
    }
    else
    {
        tmpArray = @[@762140.00,@786600.00,@160000.00,@786600.00,@786600.00,@786600.00];
    }
    NSLog(@"---chartValueSelected---value: %g", entry.y);
    NSLog(@"---chartValueSelected---value: %@", entry.data);

    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    paragraphStyle.alignment = NSTextAlignmentCenter;

    NSString *contentStr = [NSString stringWithFormat:@"%@\n%.2f",titleArray[[entry.data intValue]],[tmpArray[[entry.data intValue]] floatValue]];


    NSMutableAttributedString *centerText = [[NSMutableAttributedString alloc] initWithString:contentStr];
    [centerText setAttributes:@{
                                NSFontAttributeName: [UIFont PFSCRegularFontWithSize:12.f],
                                NSParagraphStyleAttributeName: paragraphStyle
                                } range:NSMakeRange(0, centerText.length)];
    [centerText addAttributes:@{
                                NSFontAttributeName: [UIFont PFSCRegularFontWithSize:12.f],
                                NSForegroundColorAttributeName: UIColor.gray9
                                } range:NSMakeRange(0, [titleArray[[entry.data intValue]] length])];
    [centerText addAttributes:@{
                                NSFontAttributeName: [UIFont AsapMeidumFontWithSize:14.f],
                                NSForegroundColorAttributeName: [UIColor gray3]
                                } range:NSMakeRange([titleArray[[entry.data intValue]] length], centerText.length - [titleArray[[entry.data intValue]] length])];
    _chartView.centerAttributedText = centerText;


}

- (void)chartValueNothingSelected:(ChartViewBase * __nonnull)chartView
{
    NSLog(@"chartValueNothingSelected");
}


- (void)setupPieChartView:(PieChartView *)chartView
{
    chartView.usePercentValuesEnabled = NO;
    chartView.drawSlicesUnderHoleEnabled = NO;
    chartView.holeRadiusPercent = 0.58;
    chartView.transparentCircleRadiusPercent = 0.61;
    chartView.chartDescription.enabled = NO;
    [chartView setExtraOffsetsWithLeft:5.f top:10.f right:5.f bottom:5.f];
    chartView.drawCenterTextEnabled = YES;

    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    paragraphStyle.alignment = NSTextAlignmentCenter;

    NSMutableAttributedString *centerText;
    if (!_circlePartArray) {
        centerText = [[NSMutableAttributedString alloc] initWithString:@"xxxx\n762140.00"];
    }
    else
    {
        NSString *contentStr = [NSString stringWithFormat:@"xxxx\n%.2f",[_circlePartArray[0] floatValue]];
        centerText = [[NSMutableAttributedString alloc] initWithString:contentStr];
    }
    [centerText setAttributes:@{
                                NSFontAttributeName: [UIFont PFSCRegularFontWithSize:12.f],
                                NSParagraphStyleAttributeName: paragraphStyle
                                } range:NSMakeRange(0, centerText.length)];
    [centerText addAttributes:@{
                                NSFontAttributeName: [UIFont PFSCRegularFontWithSize:12.f],
                                NSForegroundColorAttributeName: UIColor.gray9
                                } range:NSMakeRange(0, 4)];
    [centerText addAttributes:@{
                                NSFontAttributeName: [UIFont AsapMeidumFontWithSize:14.f],
                                NSForegroundColorAttributeName: [UIColor gray3]
                                } range:NSMakeRange(4, centerText.length - 4)];
    chartView.centerAttributedText = centerText;

    chartView.drawHoleEnabled = YES;
    chartView.rotationAngle = 0.0;
    chartView.rotationEnabled = YES;
    chartView.highlightPerTapEnabled = YES;

    ChartLegend *l = chartView.legend;
    l.horizontalAlignment = ChartLegendHorizontalAlignmentRight;
    l.verticalAlignment = ChartLegendVerticalAlignmentTop;
    l.orientation = ChartLegendOrientationVertical;
    l.drawInside = NO;
    l.xEntrySpace = 7.0;
    l.yEntrySpace = 0.0;
    l.yOffset = 0.0;
}
@end
Copy the code