[英]Java get java.awt.Color from string
所以我有一个看起来像这样的字符串: text java.awt.Color[r=128,g=128,b=128]text 1234
我怎样才能弹出颜色并获取 rgb 值?
您可以使用以下命令从该字符串中获取 rgb 值:
String str = "text java.awt.Color[r=128,g=128,b=128]text 1234";
String[] temp = str.split("[,]?[r,g,b][=]|[]]");
String[] colorValues = new String[3];
int index = 0;
for (String string : temp) {
try {
Integer.parseInt(string);
colorValues[index] = string;
index++;
} catch (Exception e) {
}
}
System.out.println(Arrays.toString(colorValues)); //to verify the output
上面的示例提取字符串数组中的值,如果您想要 ints 数组:
String str = "text java.awt.Color[r=128,g=128,b=128]text 1234";
String[] temp = str.split("[,]?[r,g,b][=]|[]]");
int[] colorValues = new int[3];
int index = 0;
for (String string : temp) {
try {
colorValues[index] = Integer.parseInt(string);
index++;
} catch (Exception e) {
}
}
System.out.println(Arrays.toString(colorValues)); //to verify the output
如前所述,您将需要解析文本。 这将允许您从字符串内部返回 RGB 值。 我会尝试这样的事情。
private static int[] getColourVals(String s){
int[] vals = new int[3];
String[] annotatedVals = s.split("\\[|\\]")[1].split(","); // Split the string on either [ or ] and then split the middle element by ,
for(int i = 0; i < annotatedVals.length; i++){
vals[i] = Integer.parseInt(annotatedVals[i].split("=")[1]); // Split by the = and only get the value
}
return vals;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.