color工具类 hex、int与ARGB、RGB转换

public class ColorUtil {
	/**
	 * int转#ARGB
	 * 
	 * @param color
	 * @return String #ARGB
	 */
	public static String convertToARGB(int color) {
		String alpha = Integer.toHexString(Color.alpha(color));
		String red = Integer.toHexString(Color.red(color));
		String green = Integer.toHexString(Color.green(color));
		String blue = Integer.toHexString(Color.blue(color));
		if (alpha.length() == 1) {
			alpha = "0" + alpha;
		}

		if (red.length() == 1) {
			red = "0" + red;
		}

		if (green.length() == 1) {
			green = "0" + green;
		}

		if (blue.length() == 1) {
			blue = "0" + blue;
		}

		return "#" + alpha + red + green + blue;
	}

	/**
	 * int转#RGB
	 * 
	 * @param color
	 * @return String #RGB
	 */
	public static String convertToRGB(int color) {
		String red = Integer.toHexString(Color.red(color));
		String green = Integer.toHexString(Color.green(color));
		String blue = Integer.toHexString(Color.blue(color));

		if (red.length() == 1) {
			red = "0" + red;
		}

		if (green.length() == 1) {
			green = "0" + green;
		}

		if (blue.length() == 1) {
			blue = "0" + blue;
		}

		return "#" + red + green + blue;
	}

	/**
	 * string#RGB转int
	 * 
	 * @param argb
	 * @throws NumberFormatException
	 */
	public static int convertToColorInt(String argb)
			throws IllegalArgumentException {

		if (!argb.startsWith("#")) {
			argb = "#" + argb;
		}

		return Color.parseColor(argb);
	}
}
	/**
	 * HEX颜色 转 RGB颜色
		 * @param hex 8位
	 * @return int[]
	 */
	public static int[] hexToRGB(String hex) {
		int[] rgb = new int[3];
		if (!Pattern.matches("^#[0-9a-f[A-F]]{6}", hex)) {
			return rgb;
		}


		String redStr = hex.substring(1, 3);
		String greenStr = hex.substring(3, 5);
		String blueStr = hex.substring(5);
		rgb[0] = Integer.valueOf(redStr, 16).intValue(); // R
		rgb[1] = Integer.valueOf(greenStr, 16).intValue(); // G
		rgb[2] = Integer.valueOf(blueStr, 16).intValue(); // B
		return rgb;
	}


你可能感兴趣的:(Android)