Core-Plot PieChart Slice color
Asked Answered
A

4

10

I am using core plot in one of my iPhone projects. Is it possible to change the color for a selected slice in a pie chart (using CPPieChartDataSource, CPPieChartDelegate)?

Amitie answered 2/9, 2010 at 16:55 Comment(0)
S
18

Implement the following method in your pie chart datasource:

-(CPTFill *)sliceFillForPieChart:(CPTPieChart *)pieChart recordIndex:(NSUInteger)index; 

CPFill can be a color, image, or gradient.

Shelled answered 2/9, 2010 at 23:33 Comment(1)
I want to change the color of a particular slice when it is selected. Is that possible?Amitie
M
5

In your .h file

#import "CPTPieChart.h"
@interface YourViewController : UIViewController<CPTPlotDataSource,CPTPieChartDataSource, CPTPieChartDelegate>
{   
}

in your .m file

-(CPTFill *)sliceFillForPieChart:(CPTPieChart *)pieChart recordIndex:(NSUInteger)index
{    
    CPTFill *areaGradientFill ;

    if (index==0)
        return areaGradientFill= [CPTFill fillWithColor:[CPTColor orangeColor]];
    else if (index==1)
        return areaGradientFill= [CPTFill fillWithColor:[CPTColor greenColor]];
    else if (index==2)
        return areaGradientFill= [CPTFill fillWithColor:[CPTColor yellowColor]];

    return areaGradientFill;
}

It will change PieChart Slice color. Thanks

Murther answered 28/5, 2013 at 14:48 Comment(0)
C
1

I added this to my .m file (which is the data source file for the pie chart). The colors are ugly -- just used them to test as they are really different than the defaults. And there are only three slices in my chart, hence the hard-coded 3 colors. I found the Core Plot documentation helpful for all this. Here's the link to the fillWithColor method documentation. NOTE: You need to use CPT as a prefix now, not the old CP.

-(CPTFill *)sliceFillForPieChart:(CPTPieChart *)pieChart recordIndex:(NSUInteger)index;
  {
     CPTFill *color;

     if (index == 0) {     
      color = [CPTFill fillWithColor:[CPTColor purpleColor]]; 

    } else if (index == 1) {
      color = [CPTFill fillWithColor:[CPTColor blueColor]];


    } else {
      color = [CPTFill fillWithColor:[CPTColor blackColor]];
            }

        return color;
 }

Sorry if I messed up the answer entry -- this is my first ever post on StackOverflow

Celindaceline answered 4/8, 2014 at 11:19 Comment(0)
H
0

Swift version:

func sliceFillForPieChart (pieChart: CPTPieChart, recordIndex: UInt) -> CPTFill {
    switch (recordIndex+1) {
    case 1:
        return CPTFill(color:CPTColor.greenColor());
    case 2:

        return CPTFill(color:CPTColor.redColor());
    default:
        return CPTFill(color:CPTColor.orangeColor());
    }

}
Hauser answered 8/1, 2015 at 2:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.