Convert number to grayscale in Java

I am trying to figure out how I can convert a number from 1 to 50 to a shade of gray, which can be used here:

g.setColor(MyGreyScaleColour); 

1 will be the lightest (white), and 50 will be the darkest (black).

eg.

 Color intToCol(int colNum) { code here } 

Any suggestions?

+4
source share
2 answers

Java uses RGB colors, where each component (red, green, blue) is in the range from 0 to 255. When all components have the same value, you get white-black-gray color. Combinations closer to 255 will be whiter and closer to 0 will be black. The function below will return a grayish color, while the amount of white will be reduced accordingly by input.

 Color intToCol(int colNum) { int rgbNum = 255 - (int) ((colNum/50.0)*255.0); return new Color (rgbNum,rgbNum,rgbNum); } 
+10
source

Sort of:

 float grey = (50 - colNum) / 49f; return new Color(grey, grey, grey); 
+8
source

Source: https://habr.com/ru/post/1308988/


All Articles