Converting a number to a greyscale color in Java

被刻印的时光 ゝ 提交于 2020-01-03 17:19:46

问题


I'm trying to figure out how I can convert a number between 1 and 50 to a greyscale color that could be used here:

g.setColor(MyGreyScaleColour);

1 would be lightest (white) and 50 would be darkest (black).

e.g.

Color intToCol(int colNum)  
{  
code here  
}  

Any suggestions?


回答1:


Java uses RGB colors where each component (Red, Green, Blue) ranges from 0-255. When all components have the same value, you end up with a white-black-gray color. Combinations closer to 255 would be more white and closer to 0 would be all black. The function below would return a grayish color, with the amount of white scaled accordingly with the input.

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



回答2:


Something like:

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


来源:https://stackoverflow.com/questions/2780546/converting-a-number-to-a-greyscale-color-in-java

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