Skip to content

Instantly share code, notes, and snippets.

@SimonSchubert
Created March 13, 2020 12:12
Show Gist options
  • Save SimonSchubert/7041bb0424949627f2fedbd37bc2cacb to your computer and use it in GitHub Desktop.
Save SimonSchubert/7041bb0424949627f2fedbd37bc2cacb to your computer and use it in GitHub Desktop.
import java.lang.IllegalArgumentException
import kotlin.math.floor
import kotlin.math.roundToInt
/**
* Pass a hue value/degree between 0 and 360 or pass nothing and generate a random value. Returns a random flat color as hex string.
*/
fun flatColor(deg: Float? = null): String {
val h = if (deg == null) {
val phi = 0.618033988749895
val hue = (floor(Math.random() * (360 - 0 + 1) + 0)) / 360
((hue + (hue / phi)) % 360).toFloat()
} else {
deg / 360f
}
var v = floor(Math.random() * (100 - 20 + 1) + 20)
val s = (v - 10) / 100f
v /= 100f
val i = floor(h * 6.0)
val f = h * 6 - i
val p = v * (1 - s)
val q = v * (1 - f * s)
val t = v * (1 - (1 - f) * s)
val (rr, gr, br) = when (i % 6) {
0.0 -> Triple(v, t, p)
1.0 -> Triple(q, v, p)
2.0 -> Triple(p, v, t)
3.0 -> Triple(p, q, v)
4.0 -> Triple(t, p, v)
5.0 -> Triple(v, q, p)
else -> throw IllegalArgumentException()
}
val r = (rr * 255).roundToInt()
val g = (gr * 255).roundToInt()
val b = (br * 255).roundToInt()
return "#" + ((1 shl 24) + (r shl 16) + (g shl 8) + b).toString(16).slice(IntRange(1, 6))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment