如何将字符串转换为const类的int值?

时间:2012-01-21 11:19:43

标签: java android swing android-widget

我有变量:

String colorName = "BLUE";

我想将此颜色设置为android应用程序中的paint。它应该是这样的:

paint.setColor ("Color." + colorName);

但是我收到错误警告,因为setColor()函数的参数应该是int。 有什么想法?谢谢。

5 个答案:

答案 0 :(得分:6)

也许你想要这个版本。

paint.setColor(Color.parseColor(String color)

http://developer.android.com/reference/android/graphics/Color.html#parseColor%28java.lang.String%29

答案 1 :(得分:2)

你需要这样做:

paint.setColor(Color.BLUE);

答案 2 :(得分:2)

试试这个:

protected static final int colorName = Color.BLUE;
paint.setColor(colorName);

编辑:正如我所见,你将你的颜色作为一个字符串。 所以你必须检查它是什么颜色,然后设置'colorName'变量。 像这样:

if(yourcolorstring.equals("Blue")){
     colorName = Color.BLUE;
}else if(yourcolorstring.equals("Black")){
     colorName = Color.BLACK;
}else{
     colorName = Color.WHITE;
}

答案 3 :(得分:2)

如果您有很长的颜色列表而且您不想编写一长串if ... else if语句,那么您也可以使用Map 。键是具有颜色名称的字符串,值是您要查找的Color常量值。例如:

Map<String, Color> colors = new HashMap<String, Color>();
colors.put("BLUE", Color.BLUE);
colors.put("RED", Color.RED);
colors.put("GREEN", Color.GREEN);

// To find the Color constant, look it up in the map:
String text = "BLUE";
Color c = colors.get(text);
if (c != null) {
    paint.setColor(c);
} else {
    System.out.println("Unknown color: " + text);
}

答案 4 :(得分:1)

至少在标准Java中可以使用:

import javax.swing.text.html.CSS;

String colorName = "fuchsia"; // "maroon", "rgb(1,20,30)", "#ff00aa"
Color color = CSS.stringToColor(colorName);

这是因为HTML支持;你也可以用

写一个JLabel
"<html><span style='color:blue'>hello</span>"

Oracle的JDK 7 要显示哪些文本常量可行以及格式是什么:

 /**
  * Convert a "#FFFFFF" hex string to a Color.
  * If the color specification is bad, an attempt
  * will be made to fix it up.
  */
static final Color hexToColor(String value) {
    String digits;
    int n = value.length();
    if (value.startsWith("#")) {
        digits = value.substring(1, Math.min(value.length(), 7));
    } else {
        digits = value;
    }
    String hstr = "0x" + digits;
    Color c;
    try {
        c = Color.decode(hstr);
    } catch (NumberFormatException nfe) {
        c = null;
    }
     return c;
 }

/**
 * Convert a color string such as "RED" or "#NNNNNN" or "rgb(r, g, b)"
 * to a Color.
 */
static Color stringToColor(String str) {
  Color color;

  if (str == null) {
      return null;
  }
  if (str.length() == 0)
    color = Color.black;
  else if (str.startsWith("rgb(")) {
      color = parseRGB(str);
  }
  else if (str.charAt(0) == '#')
    color = hexToColor(str);
  else if (str.equalsIgnoreCase("Black"))
    color = hexToColor("#000000");
  else if(str.equalsIgnoreCase("Silver"))
    color = hexToColor("#C0C0C0");
  else if(str.equalsIgnoreCase("Gray"))
    color = hexToColor("#808080");
  else if(str.equalsIgnoreCase("White"))
    color = hexToColor("#FFFFFF");
  else if(str.equalsIgnoreCase("Maroon"))
    color = hexToColor("#800000");
  else if(str.equalsIgnoreCase("Red"))
    color = hexToColor("#FF0000");
  else if(str.equalsIgnoreCase("Purple"))
    color = hexToColor("#800080");
  else if(str.equalsIgnoreCase("Fuchsia"))
    color = hexToColor("#FF00FF");
  else if(str.equalsIgnoreCase("Green"))
    color = hexToColor("#008000");
  else if(str.equalsIgnoreCase("Lime"))
    color = hexToColor("#00FF00");
  else if(str.equalsIgnoreCase("Olive"))
    color = hexToColor("#808000");
  else if(str.equalsIgnoreCase("Yellow"))
    color = hexToColor("#FFFF00");
  else if(str.equalsIgnoreCase("Navy"))
    color = hexToColor("#000080");
  else if(str.equalsIgnoreCase("Blue"))
    color = hexToColor("#0000FF");
  else if(str.equalsIgnoreCase("Teal"))
    color = hexToColor("#008080");
  else if(str.equalsIgnoreCase("Aqua"))
    color = hexToColor("#00FFFF");
  else if(str.equalsIgnoreCase("Orange"))
    color = hexToColor("#FF8000");
  else
      color = hexToColor(str); // sometimes get specified without leading #
  return color;
}

/**
 * Parses a String in the format <code>rgb(r, g, b)</code> where
 * each of the Color components is either an integer, or a floating number
 * with a % after indicating a percentage value of 255. Values are
 * constrained to fit with 0-255. The resulting Color is returned.
 */
private static Color parseRGB(String string) {
    // Find the next numeric char
    int[] index = new int[1];

    index[0] = 4;
    int red = getColorComponent(string, index);
    int green = getColorComponent(string, index);
    int blue = getColorComponent(string, index);

    return new Color(red, green, blue);
}

/**
 * Returns the next integer value from <code>string</code> starting
 * at <code>index[0]</code>. The value can either can an integer, or
 * a percentage (floating number ending with %), in which case it is
 * multiplied by 255.
 */
private static int getColorComponent(String string, int[] index) {
    int length = string.length();
    char aChar;

    // Skip non-decimal chars
    while(index[0] < length && (aChar = string.charAt(index[0])) != '-' &&
          !Character.isDigit(aChar) && aChar != '.') {
        index[0]++;
    }

    int start = index[0];

    if (start < length && string.charAt(index[0]) == '-') {
        index[0]++;
    }
    while(index[0] < length &&
                     Character.isDigit(string.charAt(index[0]))) {
        index[0]++;
    }
    if (index[0] < length && string.charAt(index[0]) == '.') {
        // Decimal value
        index[0]++;
        while(index[0] < length &&
              Character.isDigit(string.charAt(index[0]))) {
            index[0]++;
        }
    }
    if (start != index[0]) {
        try {
            float value = Float.parseFloat(string.substring
                                           (start, index[0]));

            if (index[0] < length && string.charAt(index[0]) == '%') {
                index[0]++;
                value = value * 255f / 100f;
            }
            return Math.min(255, Math.max(0, (int)value));
        } catch (NumberFormatException nfe) {
            // Treat as 0
        }
    }
    return 0;
}