[英]How to get RGB value from hexadecimal color code in java
我有一個十進制顏色代碼(例如: 4898901
)。 我將其轉換為4ac055
的十六進制等效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;
試試這個,
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
如果你有一個字符串,這種方式更好:
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();
我不確定你的確切需要。 不過有些提示。
整數類可以使用以下方法將十進制數轉換為十六進制數 :
Integer.toHexString(yourNumber);
要獲得RGB,您可以使用類Color:
Color color = new Color(4898901);
float r = color.getRed();
float g = color.getGreen();
float b = color.getBlue();
如果你有hex-code : 4ac055
。 前兩個字母是紅色。 接下來的兩個是綠色,兩個最新的字母是藍色。 因此,如果您有紅色的十六進制代碼,則必須將其轉換為dez。 在這些red 4a = 74
例子中。 Green c0 = 192
, blue = 85
..
嘗試創建一個分割hexcode
代碼的函數,然后返回rgb
代碼
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.