Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@siddharth96
Last active September 29, 2021 17:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siddharth96/cbb2d31509f9149e4565 to your computer and use it in GitHub Desktop.
Save siddharth96/cbb2d31509f9149e4565 to your computer and use it in GitHub Desktop.
Generate color palettes for PieChart (Android)
public int[] getPieChartColors(int numPieSlices, int baseColor,
boolean adjacentColors) {
// Inspiration http://stackoverflow.com/a/19389478
int[] colors = new int[numPieSlices];
colors[0] = baseColor;
float hsv[] = new float[3];
Color.RGBToHSV(Color.red(baseColor), Color.green(baseColor), Color.blue(baseColor),
hsv);
double step = (240.0 / (double) numPieSlices);
float baseHue = hsv[0];
for (int i = 1; i < numPieSlices; i++) {
float nextColorHue = ((float) (baseHue + step * ((float) i))) % ((float) 240.0);
colors[i] = Color.HSVToColor(new float[]{nextColorHue, hsv[1], hsv[2]});
}
if (!adjacentColors && numPieSlices > 2) {
int holder;
for (int i = 0, j = numPieSlices / 2; j < numPieSlices; i += 2, j += 2) {
// Swap
holder = colors[i];
colors[i] = colors[j];
colors[j] = holder;
}
}
return colors;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment