Convert RGB Color to HEX color

。_饼干妹妹 提交于 2021-01-29 11:05:35

问题


I am taking a color from an ImageView using OnTouchListener.

Red, Green, Blue color code can be successfully obtained, but i cant convert RGB to HEX ..

example : my rgb values are
r:21

b:16

g:228

and curresponding hex color is #15e410.

i want get #15e410. from r:21 ,b:16 ,g:228

                int pixel = bitmap.getPixel(x,y);             
                int redValue = Color.red(pixel);
                int blueValue = Color.blue(pixel);
                int greenValue = Color.green(pixel);

                int hexa=  Color.rgb(redValue, greenValue, blueValue);


                Toast.makeText(getApplicationContext(),"hexa ::"+hexa ,Toast.LENGTH_LONG).show();

回答1:


Solution:

Just use:

String hex = String.format("#%02x%02x%02x", redValue, greenValue, blueValue);

This will convert all the Red, Green and Blue values to Hex String.

Hope it helps.




回答2:


Use Integer.toHexString(color); to convert an integer to hex string.

Example:

int color = 0xff334433;
String hex = Integer.toHexString(color);
System.out.println(hex); // this prints - ff334433



回答3:


You are sending wrong the parameters to the function String.format to get the hexColor.

Try this one:

String hexColor = String.format("#%06X", redValued, greenValue, blueValue);


来源:https://stackoverflow.com/questions/52148457/convert-rgb-color-to-hex-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!