我有一个十进制颜色码(例如:4898901
)。我将它转换成相应的十六进制代码,如4ac055
。如何从十六进制颜色代码中获取红、绿和蓝色组件值?
假设这是一个字符串:
// edited to support big numbers bigger than 0x80000000
int color = (int)Long.parseLong(myColorString, 16);
int r = (color >> 16) & 0xFF;
int g = (color >> 8) & 0xFF;
int b = (color >> 0) & 0xFF;
Color color = Color.decode("0xFF0000");
int red = color.getRed();
int blue = color.getBlue();
int green = color.getGreen();
Color color = new Color(0xFF0000);
float red = color.getRed();
float green = color.getGreen();
float blue = color.getBlue();
android.graphics.Color
没有这样的方法。 - PPartisan试试这个:
colorStr e.g. "#FFFFFF"
public static Color hex2Rgb(String colorStr) {
return new Color(
Integer.valueOf( colorStr.substring( 1, 3 ), 16 ),
Integer.valueOf( colorStr.substring( 3, 5 ), 16 ),
Integer.valueOf( colorStr.substring( 5, 7 ), 16 ) );
}
使用Color类需要使用java-rt-jar-stubs-1.5.0.jar,因为Color类来自于java.awt.Color
Integer.toHexString(yourNumber);
要获取RGB值,可以使用Color类:
Color color = new Color(4898901);
float r = color.getRed();
float g = color.getGreen();
float b = color.getBlue();
String hex1 = "#FF00FF00"; //BLUE with Alpha value = #AARRGGBB
int a = Integer.valueOf( hex1.substring( 1, 3 ), 16 );
int r = Integer.valueOf( hex1.substring( 3, 5 ), 16 );
int g = Integer.valueOf( hex1.substring( 5, 7 ), 16 );
int b = Integer.parseInt( hex1.substring( 7, 9 ), 16 );
Toast.makeText(getApplicationContext(), "ARGB: " + a + " , " + r + " , "+ g + " , "+ b , Toast.LENGTH_SHORT).show();
String hex1 = "#FF0000"; //RED with NO Alpha = #RRGGBB
int r = Integer.valueOf( hex1.substring( 1, 3 ), 16 );
int g = Integer.valueOf( hex1.substring( 3, 5 ), 16 );
int b = Integer.parseInt( hex1.substring( 5, 7 ), 16 );
Toast.makeText(getApplicationContext(), "RGB: " + r + " , "+ g + " , "+ b , Toast.LENGTH_SHORT).show();
int color = Color.parseColor("#519c3f");
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
当你有一个 hex-code : 4ac055
时,前两个字母是红色。接下来的两个字母是绿色,最后两个字母是蓝色。所以当你有红色的十六进制代码时,你必须将其转换回dez。在这个例子中,red 4a = 74
。Green c0 = 192
,blue = 85
。
尝试编写一个函数,它可以拆分 hexcode
并返回 rgb
代码。