Java Color Encode encodeRGBHexString(Color color, boolean withAlpha)

Here you can find the source of encodeRGBHexString(Color color, boolean withAlpha)

Description

Create a string representation of the color in the format #RRGGBB or #RRGGBBAA if withAlpha is true.

License

Apache License

Parameter

Parameter Description
color the color to encode
withAlpha whether to include the alpha value in the result

Return

the string or null if color was null

Declaration

public static String encodeRGBHexString(Color color, boolean withAlpha) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.awt.Color;

public class Main {
    /**//www.j av  a  2s. c o m
     * Create a string representation of the color in the format <code>#RRGGBB</code> or
     * <code>#RRGGBBAA</code> if withAlpha is true. The RR is the 2 byte hex value of the red
     * component of the color.
     *
     * @param color
     *            the color to encode
     * @param withAlpha
     *            whether to include the alpha value in the result
     * @return the string or null if color was null
     */
    public static String encodeRGBHexString(Color color, boolean withAlpha) {
        if (color == null) {
            return null;
        }
        StringBuilder colorString = new StringBuilder(withAlpha ? 9 : 7);
        colorString.append("#");
        appendHexString(colorString, color.getRed());
        appendHexString(colorString, color.getGreen());
        appendHexString(colorString, color.getBlue());
        if (withAlpha) {
            appendHexString(colorString, color.getAlpha());
        }
        return colorString.toString();
    }

    private static void appendHexString(StringBuilder builder, int value) {
        String hex = Integer.toHexString(value);
        if (hex.length() == 1) {
            builder.append("0");
        }
        builder.append(hex);
    }
}

Related

  1. encodeColor(Color color)
  2. encodeColor(Color color)
  3. encodeColor(int r, int g, int b)
  4. encodeColorForCss(Color color)
  5. encodeRGB(Color color)
  6. encodeRGBIntString(Color color, boolean withAlpha)