Java Hex to Color hexToColor(final String hex)

Here you can find the source of hexToColor(final String hex)

Description

Gets the corresponding Color object for this hexidecimal string.

License

Open Source License

Declaration

public static Color hexToColor(final String hex) throws NumberFormatException 

Method Source Code


//package com.java2s;
/*// w w  w. j a v a  2s . c  o m
 * #%L
 * VisBio application for visualization of multidimensional biological
 * image data.
 * %%
 * Copyright (C) 2002 - 2014 Board of Regents of the University of
 * Wisconsin-Madison.
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 2 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-2.0.html>.
 * #L%
 */

import java.awt.Color;

public class Main {
    /** Gets the corresponding Color object for this hexidecimal string. */
    public static Color hexToColor(final String hex) throws NumberFormatException {
        if (hex == null)
            return null;
        final int len = hex.length();
        if (len == 0 || len % 3 != 0)
            return null;
        final int len3 = len / 3;
        final float max = (float) Math.pow(16, len3) - 1;
        Color color = null;
        try {
            // divide hex string into three equal parts, normalizing to (0.0 - 1.0)
            final float r = Integer.parseInt(hex.substring(0, len3), 16) / max;
            final float g = Integer.parseInt(hex.substring(len3, 2 * len3), 16) / max;
            final float b = Integer.parseInt(hex.substring(2 * len3), 16) / max;
            color = new Color(r, g, b);
        } catch (final NumberFormatException exc) {
            throw exc;
        }
        return color;
    }
}

Related

  1. hexToColor(String color)
  2. hexToColor(String color)
  3. hexToColor(String colorHex)
  4. hexToColor(String hex)