How to convert hex to rgb using Java?

后端 未结 19 2035
-上瘾入骨i
-上瘾入骨i 2020-11-27 13:46

How can I convert hex color to RGB code in Java? Mostly in Google, samples are on how to convert from RGB to hex.

19条回答
  •  时光取名叫无心
    2020-11-27 14:12

    For Android Kotlin users:

    "#FFF".longARGB()?.let{ Color.parceColor(it) }
    "#FFFF".longARGB()?.let{ Color.parceColor(it) }
    
    fun String?.longARGB(): String? {
        if (this == null || !startsWith("#")) return null
        
    //    #RRGGBB or #AARRGGBB
        if (length == 7 || length == 9) return this
    
    //    #RGB or #ARGB
        if (length in 4..5) {
            val rgb = "#${this[1]}${this[1]}${this[2]}${this[2]}${this[3]}${this[3]}"
            if (length == 5) {
                return "$rgb${this[4]}${this[4]}"
            }
            return rgb
        }
    
        return null
    }
    

提交回复
热议问题