Last active
January 5, 2018 21:29
-
-
Save gorrotowi/3ba2a01a5acd0ba20bf8afd0743cb946 to your computer and use it in GitHub Desktop.
How to set Alpha for HexColor
This file contains 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
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