Java examples for 2D Graphics:Text
Attempts to parse an RGB triplet or an RGBA quadruplet from the string.
/**/*from w ww .j ava2s.c o m*/ * Copyright 1998-2008, CHISEL Group, University of Victoria, Victoria, BC, Canada. * All rights reserved. */ //package com.java2s; import java.awt.Color; public class Main { /** * Attempts to parse an RGB triplet or an RGBA quadruplet from the string. * It searches through each character and tries to pull out 3 or 4 integers (between 0-255) * to use for red, green, blue, and alpha. * @param value the string to parse * @return the {@link Color} or null */ public static Color rgbStringToColor(String value) { Color c = null; if ((value != null) && (value.length() > 0)) { int[] rgba = { -1, -1, -1, 255 }; StringBuffer buffer = new StringBuffer(3); ; boolean inNumber = false; int index = 0; try { if (Character.isDigit(value.charAt(value.length() - 1))) { // handles the case where the last character is a number value = value + " "; } for (int i = 0; (i < value.length()) && (index < rgba.length); i++) { char ch = value.charAt(i); if (Character.isDigit(ch)) { inNumber = true; buffer.append(ch); } else if (inNumber) { inNumber = false; int num = Integer.parseInt(buffer.toString()); num = Math.max(0, Math.min(255, num)); rgba[index++] = num; buffer = new StringBuffer(3); } } if (index >= 3) { c = new Color(rgba[0], rgba[1], rgba[2], rgba[3]); } } catch (NumberFormatException ignore) { } } return c; } }