解析“rgb(x,x,x)”字符串到一个颜色对象 [英] Parsing a "rgb (x, x, x)" String Into a Color Object
问题描述
我宁愿有一个GWT选项。我也意识到,使用像Scanner.nextInt这样的东西很容易。然而我正在寻找一种更可靠的方式来获取这些信息。
据我所知,进入Java或GWT。您必须编写自己的方法:
public static Color parse(String input)
{
模式c = Pattern.compile(rgb * \\(*([0-9] +),*([0-9] +),*([0-9] +)* \\ ));
Matcher m = c.matcher(input);
如果(m.matches())
{
返回新颜色(Integer.valueOf(m.group(1)),// r
整数。 valueOf(m.group(2)),// g
Integer.valueOf(m.group(3))); // b
}
返回null;
$ / code>
您可以像这样使用
// java.awt.Color [r = 128,g = 32,b = 212]
System.out.println(parse(rgb(128 ,32212)));
// java.awt.Color [r = 255,g = 0,b = 255]
System.out.println(parse(rgb(255,0,255) ));
//抛出IllegalArgumentException:
//颜色参数超出预期范围:红色蓝色
System.out.println(parse(rgb(256,1,300)) ));
Is there an effecient way/existing solution for parsing the string "rgb (x, x, x)" [where x in this case is 0-255] into a color object? [I'm planning to use the color values to convert them into the hex color equivilience.
I would prefer there to be a GWT option for this. I also realize that it would be easy to use something like Scanner.nextInt. However I was looking for a more reliable manner to get this information.
As far as I know there's nothing like this built-in to Java or GWT. You'll have to code your own method:
public static Color parse(String input)
{
Pattern c = Pattern.compile("rgb *\\( *([0-9]+), *([0-9]+), *([0-9]+) *\\)");
Matcher m = c.matcher(input);
if (m.matches())
{
return new Color(Integer.valueOf(m.group(1)), // r
Integer.valueOf(m.group(2)), // g
Integer.valueOf(m.group(3))); // b
}
return null;
}
You can use that like this
// java.awt.Color[r=128,g=32,b=212]
System.out.println(parse("rgb(128,32,212)"));
// java.awt.Color[r=255,g=0,b=255]
System.out.println(parse("rgb (255, 0, 255)"));
// throws IllegalArgumentException:
// Color parameter outside of expected range: Red Blue
System.out.println(parse("rgb (256, 1, 300)"));
这篇关于解析“rgb(x,x,x)”字符串到一个颜色对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!