繁体   English   中英

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

[英]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 = 192blue = 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM