Search code examples
kotlingraphicsbitmaprgbandroidx

Palette.getDominantColor() return a negative number. RGB packet int


I'm trying to pick the dominant color from a bitmap using Palette:

val p: Palette = Palette.from(bitmap!!).generate()
Log.d(TAG, "${p.getDominantColor(0)}")

And the output is -8341352

From reference the value returned is a RGB packet int. So how can I get the real information of color? I can't find the comparison to an RGB value from a negative integer with seven-digit


Solution

  • Use the Color utility functions to extract the RGBA components of the color as integers in the range 0-255 inclusive.

    val argb = p.getDominantColor(0)
    val a = Color.alpha(argb)
    val r = Color.red(argb)
    val g = Color.green(argb)
    val b = Color.blue(argb)
    

    If you're using androidx core-ktx library (default projects probably already are), you can get them by destructuring:

    val (a, r, g, b) = p.getDominantColor(0)
    

    If you want the values as floats in the range 0..1, you can divide the above values by 255f, or if your min SDK version is at least 26 you can use destructuring like this (note A is last instead of first when working with the Color class rather than an Int that represents a color):

    val argb = p.getDominantColor(0)
    val (r, g, b, a) = Color.valueOf(argb)