Java Color Decode decodeColor(String string)

Here you can find the source of decodeColor(String string)

Description

decodes a String containing a 4 byte hex value as a color with an optional alpha (transparency) channel.

License

LGPL

Declaration

public static Color decodeColor(String string) 

Method Source Code


//package com.java2s;
// licensed under GNU LGPL

import java.awt.Color;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    /**//from  ww w.  j a  v a 2 s  .  co m
     * decodes a String containing a 4 byte hex value as a color
     * with an optional alpha (transparency) channel. A zero
     * transparency byte is treated as an opaque color.
     */
    public static Color decodeColor(String string) {
        if (string == null)
            return Color.BLACK;

        // decode a string of the form: "java.awt.Color[r=51,g=102,b=153]"
        if (string.startsWith("java.awt.Color")) {
            Pattern pattern = Pattern.compile("java.awt.Color\\[r=(\\d+),\\s*g=(\\d+),\\s*b=(\\d+)\\s*\\]");
            Matcher m = pattern.matcher(string);
            if (m.matches()) {
                int r = Integer.parseInt(m.group(1));
                int g = Integer.parseInt(m.group(2));
                int b = Integer.parseInt(m.group(3));
                return new Color(r, g, b);
            }
        }

        // use Long.decode 'cause Integer.decode is broken for hex
        // values with the sign bit set. (bastards!)
        int c = Long.decode(string).intValue();
        // c >>> 24 > 0 checks for a transparency (alpha channel)
        // if alpha channel is zero, we return an opaque color by
        // setting hasAplha to false.
        return new Color(c, c >>> 24 > 0);
    }
}

Related

  1. decodeColor(final double v)
  2. decodeColor(final String value)
  3. decodeColor(int color)
  4. decodeColor(int value)
  5. decodeColor(String color, Color defaultColor)
  6. decodeColor(String value, Color dflt)
  7. decodeHexColor(String hexString)
  8. decodeHtmlColorString(String colourString)
  9. decodeRGB(String color)