Returns the opacity component of the ARGB color as a decimal format. - Java 2D Graphics

Java examples for 2D Graphics:Color RGB

Description

Returns the opacity component of the ARGB color as a decimal format.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String argb = "java2s.com";
        System.out.println(getOpacityFromARGB(argb));
    }// w  ww .  ja v a 2  s .com

    /**
     * Returns the opacity component of the ARGB color as a decimal format.
     *
     * @param argb Color in HEX format (either with or without alpha, e.g.
     *             #CCCCCC or #ffCCCCCC.
     * @return Value between 0.0...1.0 where 0.0 is completely transparent
     * and 1.0 means no transparency.
     */
    public static double getOpacityFromARGB(String argb) {
        int[] components = getARGBComponents(argb);
        double opacity = components[0] / 255.0;

        if (opacity > 1.0) {
            opacity = 1.0;
        } else if (opacity < 0.0) {
            opacity = 0.0;
        }

        return opacity;
    }

    /**
     * Return ARGB values in int array
     * @param argb Color in HEX format (either with or without alpha, e.g.
     *             #CCCCCC or #ffCCCCCC.
     * @return
     */
    private static int[] getARGBComponents(String argb) {

        if (argb.startsWith("#")) {
            argb = argb.replace("#", "");
        }

        int alpha = -1, red = -1, green = -1, blue = -1;

        if (argb.length() == 8) {
            alpha = Integer.parseInt(argb.substring(0, 2), 16);
            red = Integer.parseInt(argb.substring(2, 4), 16);
            green = Integer.parseInt(argb.substring(4, 6), 16);
            blue = Integer.parseInt(argb.substring(6, 8), 16);
        } else if (argb.length() == 6) {
            alpha = 255;
            red = Integer.parseInt(argb.substring(0, 2), 16);
            green = Integer.parseInt(argb.substring(2, 4), 16);
            blue = Integer.parseInt(argb.substring(4, 6), 16);
        }

        int[] components = { alpha, red, green, blue };

        return components;

    }
}

Related Tutorials