如何从java中的十六进制颜色代码中获取RGB值

问题描述 投票:16回答:7

我有一个十进制颜色代码(例如:4898901)。我将其转换为十六进制等效于4ac055。如何从十六进制颜色代码中获取红色,绿色和蓝色组件值?

java android colors
7个回答
66
投票

假设这是一个字符串:

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

7
投票

试试这个,

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


7
投票

如果你有一个字符串,这种方式更好:

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();

5
投票

我不确定你的确切需要。不过有些提示。

Integer class can transform a decimal number to its hexadecimal representation的方法:

Integer.toHexString(yourNumber);

要获得RGB,您可以使用类Color:

Color color = new Color(4898901);
float r = color.getRed();
float g = color.getGreen();
float b = color.getBlue();

1
投票

当你有hex-code : 4ac055。前两个字母是红色。接下来的两个是绿色,两个最新的字母是蓝色。因此,如果您有红色的十六进制代码,则必须将其转换为dez。在这些例子中red 4a = 74Green c0 = 192blue = 85 ..

尝试制作一个分割hexcode的函数,然后返回rgb代码


0
投票
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();

0
投票
int color = Color.parseColor("#519c3f");

int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
© www.soinside.com 2019 - 2024. All rights reserved.