gpt4 book ai didi

java - 将 "rgb (x, x, x)"字符串解析为颜色对象

转载 作者:太空狗 更新时间:2023-10-29 22:43:28 24 4
gpt4 key购买 nike

是否有有效的方法/现有解决方案来将字符串“rgb (x, x, x)”[这里的 x 是 0-255] 解析为颜色对象? [我打算使用颜色值将它们转换为十六进制颜色等值。

我希望为此提供 GWT 选项。我还意识到使用像 Scanner.nextInt 这样的东西会很容易。然而,我一直在寻找一种更可靠的方式来获取这些信息。

最佳答案

据我所知,Java 或 GWT 中没有这样的内置功能。您必须编写自己的方法:

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;
}

你可以这样使用它

// 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)"));

关于java - 将 "rgb (x, x, x)"字符串解析为颜色对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7613996/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com