Skip to content

Instantly share code, notes, and snippets.

@gorrotowi
Last active January 5, 2018 21:29
Show Gist options
  • Save gorrotowi/3ba2a01a5acd0ba20bf8afd0743cb946 to your computer and use it in GitHub Desktop.
Save gorrotowi/3ba2a01a5acd0ba20bf8afd0743cb946 to your computer and use it in GitHub Desktop.
How to set Alpha for HexColor
import kotlin.math.roundToInt
fun main(args: Array<String>) {
println("#2c79a5".alphaColor(0.5F))
println(getColorIntWithAlpha("#2c79a5",0.5F))
}
fun getColorIntWithAlpha(hexColor: String, alpha: Float): Int =
Color.parseColor(hexColor.alphaColor(alpha))
fun String.alphaColor(percentage: Float): String = if (percentage < 0 || percentage > 1) {
fail("The percentage need to be a float number between 0.0 and 1.0")
} else {
val alphInt = ((percentage * 255) + 0.000001).roundToInt()
val alphaHex = String.format("%02X", alphInt)
this.replace("#", "#$alphaHex")
}
fun fail(message: String): Nothing {
throw IllegalArgumentException(message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment