Java Color Create toColor(final String hexColor)

Here you can find the source of toColor(final String hexColor)

Description

Converts hex color representation to java.awt.Color object.

License

Open Source License

Parameter

Parameter Description
hexColor hex color representation (ex. "8822DDC0", where 88 - red, 22 - green, DD - blue, C0 - alpha).

Return

java.awt.Color object

Declaration

public static Color toColor(final String hexColor) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.Color;

public class Main {
    private static final int RED_BEGIN_INDEX = 0;
    private static final int RED_END_INDEX = 2;
    private static final int GREEN_BEGIN_INDEX = 2;
    private static final int GREEN_END_INDEX = 4;
    private static final int BLUE_BEGIN_INDEX = 4;
    private static final int BLUE_END_INDEX = 6;
    private static final int ALPHA_BEGIN_INDEX = 6;
    private static final int ALPHA_END_INDEX = 8;
    private static final int HEX_RADIX = 16;

    /**/*  ww w  .j a va 2s  .  c o  m*/
     * Converts hex color representation to java.awt.Color object.
     *
     * @param hexColor hex color representation (ex. "8822DDC0", where 88 - red, 22 - green, DD - blue, C0 - alpha).
     * @return java.awt.Color object
     */
    public static Color toColor(final String hexColor) {
        Color color = null;
        if (hexColor.length() == ALPHA_END_INDEX) {
            final String red = hexColor.substring(RED_BEGIN_INDEX, RED_END_INDEX);
            final String green = hexColor.substring(GREEN_BEGIN_INDEX, GREEN_END_INDEX);
            final String blue = hexColor.substring(BLUE_BEGIN_INDEX, BLUE_END_INDEX);
            final String alpha = hexColor.substring(ALPHA_BEGIN_INDEX, ALPHA_END_INDEX);

            color = new Color(Integer.parseInt(red, HEX_RADIX), Integer.parseInt(green, HEX_RADIX),
                    Integer.parseInt(blue, HEX_RADIX), Integer.parseInt(alpha, HEX_RADIX));

        }

        return color;
    }
}

Related

  1. generateRGBRandomColor()
  2. generateTexturePaint(String text, Font font, Color textColor, Color bgColor, int width, int height)
  3. generateVisuallyDistinctColors(int ncolors, float minComponent, float maxComponent)
  4. toColor(byte red, byte green, byte blue)
  5. toColor(byte[] bytes)
  6. toColor(final String hexString)
  7. toColor(final String text, final Color defaultValue)
  8. toColor(float[] color)
  9. toColor(int rgba)