我使用PrintWriter将颜色保存在文件中。颜色看起来像这样,它是一个字符串:java.awt.Color[r=255,g=0,b=0]
。
现在我想使用Scanner,并将此String解码为普通颜色。作为尝试,我尝试了
layer.shapeColor = Color.decode("java.awt.Color[r=255,g=0,b=0]");
但它不起作用。什么是将这种字符串更改为颜色的方法?有可能吗?
答案 0 :(得分:0)
对于您的项目来说可能有点太晚了,但是,如果您喜欢正则表达式,您可以尝试一些实现:
Scanner
:import java.awt.Color;
import java.util.Random;
import java.util.Scanner;
public class UsingScanner {
public static void main(final String[] args) {
//Generate random color components:
final Random rand = new Random();
final byte[] components = new byte[3];
rand.nextBytes(components);
//Construct random color:
final Color original = new Color(components[0] & 0xFF, components[1] & 0xFF, components[2] & 0xFF);
//Debug:
final String originalToString = original.toString();
System.out.println(originalToString);
//Scan:
final Scanner scan = new Scanner(originalToString);
scan.useDelimiter("(r|\\,g|\\,b)=|\\]").next(); //Use proper delimiter and ignore first part (which is the class name)
final int r, g, b;
System.out.println(r = scan.nextInt());
System.out.println(g = scan.nextInt());
System.out.println(b = scan.nextInt());
//Verify:
System.out.println(new Color(r, g, b).equals(original));
}
}
Pattern
:import java.awt.Color;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UsingPattern {
public static void main(final String[] args) {
//Generate random color components:
final Random rand = new Random();
final byte[] components = new byte[3];
rand.nextBytes(components);
//Construct random color:
final Color original = new Color(components[0] & 0xFF, components[1] & 0xFF, components[2] & 0xFF);
//Debug:
final String originalToString = original.toString();
System.out.println(originalToString);
//Parse:
final Matcher matcher = Pattern.compile(".+\\[r=(\\d{1,3})\\,g=(\\d{1,3}),b=(\\d{1,3})\\]").matcher(originalToString);
if (matcher.matches()) {
final int r, g, b;
System.out.println(r = Integer.parseInt(matcher.group(1)));
System.out.println(g = Integer.parseInt(matcher.group(2)));
System.out.println(b = Integer.parseInt(matcher.group(3)));
//Verify:
System.out.println(new Color(r, g, b).equals(original));
}
}
}
String
的这种默认 Color
表示,您所要求的是,您本质上丢失了 ColorSpace
信息以及 alpha
组件。Color
和 ColorSpace
实例,例如:
Serializable
。Color
似乎如 related official tutorial 中所述,而 ColorSpace
包含在 {{ 1}}).Color
似乎在其 value 中包含其所有组件(对于默认 sRGB Color
),而 ColorModel
似乎是可通过其 type 识别。