Last active
November 16, 2019 13:50
-
-
Save AndSky90/337a6b81f3ae9b6b614ae72c84e38133 to your computer and use it in GitHub Desktop.
parse RGBA-css3 colors
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
/**если цвет парсится из строки нормально, возвращаем цвет в Integer, иначе null*/ | |
fun parseItemColor(color: String?): Int? { | |
return if (color.isNullOrBlank()) | |
null | |
else | |
try { | |
Color.parseColor(color) //парсинг схемы #RRGGBB и #AARRGGBB | |
} catch (ex: IllegalArgumentException) { | |
try { //парсинг схемы "rgba(245,245,245,0.5)" | |
val splitStr = color.substring(color.indexOf('(') + 1, color.indexOf(')')) | |
val splitString = | |
splitStr.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() | |
//складываем числа между запятыми в массив | |
val colorValues = IntArray(splitString.size) | |
for (i in splitString.indices) { | |
if (i == 3) | |
//преобразовываем альфу в hexadecimal | |
colorValues[i] = (splitString[i].trim().toFloat() * 255).toInt() | |
else | |
colorValues[i] = Integer.parseInt(splitString[i].trim()) | |
} | |
if (splitString.size == 4) | |
Color.argb(colorValues[3], colorValues[0], colorValues[1], colorValues[2]) | |
else Color.rgb( colorValues[0], colorValues[1], colorValues[2]) | |
} catch (ex: Exception) { | |
log("Неудачный парс цвета, непонятная схема: $color") | |
null | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment