gets a color from a hexadecimal string like "AABBCC" or "AABBCCDD". - Java 2D Graphics

Java examples for 2D Graphics:Color String

Description

gets a color from a hexadecimal string like "AABBCC" or "AABBCCDD".

Demo Code

/** Copyright by Barry G. Becker, 2000-2011. Licensed under MIT License: http://www.opensource.org/licenses/MIT  */
//package com.java2s;
import java.awt.*;

public class Main {
    /**//from   ww w.  j  a  v a2  s.c o m
     * gets a color from a hexadecimal string like "AABBCC"
     * or "AABBCCDD". The DD in this case gives the opacity value
     * if only rgb are given, then FF is assumed for the opacity
     * @param sColor color to convert
     * @param defaultColor  color to use if sColor has a problem
     * @return the color object
     */
    public static Color getColorFromHTMLColor(String sColor,
            Color defaultColor) {
        if (sColor == null || sColor.length() < 6 || sColor.length() > 8)
            return defaultColor;

        long intColor;
        try {
            intColor = Long.decode("0x" + sColor); // NON-NLS
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("bad color format: "
                    + sColor, e);

        }
        int blue = (int) (intColor % 256);
        int green = (int) ((intColor >> 8) % 256);
        int red = (int) ((intColor >> 16) % 256);
        int opacity = 255;
        if (sColor.length() > 6) {
            opacity = (int) (intColor >> 24);
        }
        return new Color(red, green, blue, opacity);
    }
}

Related Tutorials