Java Color Create colorFromString(String string)

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

Description

Gets the color as int value from the given String .

License

Open Source License

Parameter

Parameter Description
string The String value. Should be in the format RRGGBB or RRGGBBAA .

Return

The color as int value.

Declaration

public final static int colorFromString(String string) 

Method Source Code

//package com.java2s;
/*/*from  www  . j  a  va 2  s .  co  m*/
 * Copyright (c) 2017 Robert 'Bobby' Zenz
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

public class Main {
    /**
     * Gets the color as int value from the given {@link String}.
     * 
     * @param string The {@link String} value. Should be in the format
     *        {@code RRGGBB} or {@code RRGGBBAA}.
     * @return The color as int value.
     */
    public final static int colorFromString(String string) {
        if (string == null || string.length() == 0) {
            return 0x000000ff;
        }

        String padded = "";

        if (string.length() == 6) {
            padded = string + "ff";
        } else if (string.length() > 8) {
            padded = string.substring(0, 8);
        } else {
            padded = "00000000".substring(0, 8 - string.length()) + string;
        }

        try {
            return Integer.parseInt(padded.substring(0, 2), 16) << 24
                    | Integer.parseInt(padded.substring(2, 4), 16) << 16
                    | Integer.parseInt(padded.substring(4, 6), 16) << 8
                    | Integer.parseInt(padded.substring(6, 8), 16);
        } catch (NumberFormatException e) {
            // Ignore the exception, we do not need to log it or know that it
            // happened, really.
            return 0x000000ff;
        }
    }
}

Related

  1. color(String s)
  2. color(String s)
  3. colorFromRGB(int r, int g, int b)
  4. colorFromRGB(int red, int green, int blue)
  5. colorFromRGBA(int red, int green, int blue, int alpha)
  6. colorWithARGB(int alpha, int red, int green, int blue)
  7. colorWithIntAndAlpha(int color, int alpha)
  8. generateBlankImage(int w, int h, Color col)
  9. generateColor(int fc, int bc)