1.原理
????????主要是調(diào)用了toHexString(將int類型轉(zhuǎn)為16進(jìn)制字符串)瘪菌、parseInt(將字符串解析為int)這兩個(gè)方法。
2.代碼
public static void main(String[] args) {
String hexString = colorToHexValue(Color.RED);
System.out.println("16進(jìn)制字符串:" + hexString);
Color color = fromStrToARGB(hexString);
System.out.println("16進(jìn)制字符串轉(zhuǎn)為顏色的ARGB值:("+String.valueOf(color.getAlpha())+","+String.valueOf(color.getRed())+","
+String.valueOf(color.getGreen())+","+String.valueOf(color.getBlue())+")");
}
private static String colorToHexValue(Color color) {
return intToHexValue(color.getAlpha()) + intToHexValue(color.getRed()) + intToHexValue(color.getGreen()) + intToHexValue(color.getBlue());
}
private static String intToHexValue(int number) {
String result = Integer.toHexString(number & 0xff);
while (result.length() < 2) {
result = "0" + result;
}
return result.toUpperCase();
}
private static Color fromStrToARGB(String str) {
String str1 = str.substring(0, 2);
String str2 = str.substring(2, 4);
String str3 = str.substring(4, 6);
String str4 = str.substring(6, 8);
int alpha = Integer.parseInt(str1, 16);
int red = Integer.parseInt(str2, 16);
int green = Integer.parseInt(str3, 16);
int blue = Integer.parseInt(str4, 16);
Color color = new Color(red, green, blue, alpha);
return color;
}
3.效果
效果圖.png