Created
August 21, 2019 06:26
-
-
Save imranhsn/9abd94a701431cca6cffbebd90934d4b to your computer and use it in GitHub Desktop.
Dynamically generate pie chart color based on base color and number of slices.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun getPieChartColors( | |
numPieSlices: Int, adjacentColors: Boolean | |
): IntArray { | |
val colors = IntArray(numPieSlices) | |
val baseColor = Color.parseColor("#8A56E2") | |
colors[0] = baseColor | |
val hsv = FloatArray(3) | |
Color.RGBToHSV( | |
Color.red(baseColor), Color.green(baseColor), Color.blue(baseColor), | |
hsv | |
) | |
val step = 240.0 / numPieSlices.toDouble() | |
val baseHue = hsv[0] | |
for (i in 1 until numPieSlices) { | |
val nextColorHue = (baseHue + step * i.toFloat()).toFloat() % 240.0.toFloat() | |
colors[i] = Color.HSVToColor(floatArrayOf(nextColorHue, hsv[1], hsv[2])) | |
} | |
if (!adjacentColors && numPieSlices > 2) { | |
var holder: Int | |
var i = 0 | |
var j = numPieSlices / 2 | |
while (j < numPieSlices) { | |
// Swap | |
holder = colors[i] | |
colors[i] = colors[j] | |
colors[j] = holder | |
i += 2 | |
j += 2 | |
} | |
} | |
return colors | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment