Created
February 1, 2018 23:22
-
-
Save goreilly/06d83ea3bca7e806a7190f5d0d6600dd to your computer and use it in GitHub Desktop.
Parse CSS colors in Kotlin
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
class Color(val red: Int, val green: Int, val blue: Int, val alpha: Float) { | |
companion object { | |
private val pattern = Pattern.compile("^rgba?\\((\\d+), (\\d+), (\\d+)(?:, ([\\d.]+))?\\)$") | |
fun fromString(string: String): Color? { | |
val matcher = pattern.matcher(string) | |
if (!matcher.matches()) return null | |
val red = matcher.group(1).toInt() | |
val green = matcher.group(2).toInt() | |
val blue = matcher.group(3).toInt() | |
val alpha = matcher.group(4)?.toFloat() ?: 1.0f | |
return Color(red, green, blue, alpha) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment