Search code examples
androidcolor-pickercolor-codes

Android: Color codes


I am implementing color picker using the library from AmbilWarna, with alpha being turned on.

Sample code is as follows: https://code.google.com/p/android-color-picker/

While a color code is returned,

  • bright green with middle transparency: color code = 1980104448
  • bright yellow with middle transparency: color code = 1912340224
  • bright red with no transparency: color code = -65536 (negative?)
  • white with no transparency: color code = -1
  • white with 100% transparency: color code = 16777215

Question:

I would like to use these returned color code to set the background color of the buttons. How could these color codes be interpreted? And why are some being negative? Is it necessary to convert to RGB codes?


Solution

  • All values are in decimal.

    white with 100% transparency: color code = 16777215

    16777215(10) = FFFFFF(16)

    You need not convert this, you can directly set this.

    myView.setBackgroundColor(value);

    If you have HEX value ex "#FFFFFF", we have to set as

    myView.setBackgroundColor (Color.parseColor ("#FFFFFF"));

    Color.parseColor ("#FFFFFF"); is called, which inturn returns int

    The below method is copied from android.graphics.Color.java

    /**
     * Parse the color string, and return the corresponding color-int.
     * If the string cannot be parsed, throws an IllegalArgumentException
     * exception. Supported formats are:
     * #RRGGBB
     * #AARRGGBB
     * 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta',
     * 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey',
     * 'aqua', 'fuschia', 'lime', 'maroon', 'navy', 'olive', 'purple',
     * 'silver', 'teal'
     */
    public static int parseColor(String colorString) {
        if (colorString.charAt(0) == '#') {
            // Use a long to avoid rollovers on #ffXXXXXX
            long color = Long.parseLong(colorString.substring(1), 16);
            if (colorString.length() == 7) {
                // Set the alpha value
                color |= 0x00000000ff000000;
            } else if (colorString.length() != 9) {
                throw new IllegalArgumentException("Unknown color");
            }
            return (int)color;
        } else {
            Integer color = sColorNameMap.get(colorString.toLowerCase(Locale.ROOT));
            if (color != null) {
                return color;
            }
        }
        throw new IllegalArgumentException("Unknown color");
    }