Skip to content

Instantly share code, notes, and snippets.

@stepango
Last active May 29, 2016 04:44
Show Gist options
  • Save stepango/eb1cd93c30445d0631ea946ebb0c8495 to your computer and use it in GitHub Desktop.
Save stepango/eb1cd93c30445d0631ea946ebb0c8495 to your computer and use it in GitHub Desktop.
Gradient color utils
fun interpColor(@FloatRange(from = 0.0, to = 1.0) unit: Float, colors: IntArray): Int {
if (unit <= 0) return colors[0]
if (unit >= 1) return colors[colors.size - 1]
var p = unit * (colors.size - 1)
val i = p.toInt()
// take fractional part
p -= i
val c0 = colors[i]
val c1 = colors[i + 1]
// Calculates each channel separately
val a = avg(alpha(c0), alpha(c1), p)
val r = avg(red(c0), red(c1), p)
val g = avg(green(c0), green(c1), p)
val b = avg(blue(c0), blue(c1), p)
return Color.argb(a, r, g, b)
}
fun avg(s: Int, e: Int, @FloatRange(from = 0.0, to = 1.0) p: Float)
= s + round(p * (e - s))
@stepango
Copy link
Author

Original source could be found here https://github.com/stepango/kopi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment