Map rainbow colors to RGB

梦想的初衷 提交于 2019-12-07 16:36:15

问题


Suppose I have a class RainbowColorsMapper with the constructor RainbowColorsMapper(int n), where n>=2. Now I want to have continuous mapping of rainbow colors from red to violet which I get using the method mapper.getColor(int number) where low values correspond to red end, and high near n to violet end. If n = 2, mapper.getColor(0) returns most left color of the spectrum (near red), and mapper.getColor(1) returns the most right color. Same with bigger n with automatic scaling.

My question: can this be done relatively easy, and if yes what are suggestions on the algorithm?


回答1:


The easiest way to do this will be to work in the HSL colourspace rather than RGB. Create colours where the saturation and lightness are fixed (to 100% and 50%, i would suggest), and the hue varies between suitable endpoints (which you might need to experiment to find). Convert the HSL values to RGB using Color.getHSBColor.




回答2:


Remember that the colours of the rainbow are ordered according to wavelength, so basically in your model, n is somehow related to wavelength. So your question essentially boils down to mapping wavelength (n) to RGB. This is not an entirely trivial process, but for a start, you could check this question out:

Convert light frequency to RGB?




回答3:


Or use a Hue Saturation Value color model, and iterate over Hue.




回答4:


You basically have a hue change from 0 to 300 in the colour model

How to calculate RGB from Hue you can find on Wikipedia




回答5:


its fairly easy once you figure it out. The code underneath will allow you to cycle bewteen all existing rbg colors

  private int r=255;
  private int g=0;
  private int b=0;
  private void nextRGB()
  {
    if ( r == 255 && g < 255 && b == 0 )
      {
      g++;
      }
    if ( g == 255 && r > 0 && b == 0 )
      {
      r--;
      }
    if ( g == 255 && b < 255 && r == 0 )
      {
      b++;
      }
    if ( b == 255 && g > 0 && r == 0 )
      {
      g--;
      }
    if ( b == 255 && r < 255 && g == 0 )
      {
      r++;
      }
    if ( r == 255 && b > 0 && g == 0 )
      {
      b--;
      }
  }
  public Color nextColor()
  {
  nextRGB();
  return makeColor();
  }

  private Color makeColor()
  {
    return new Color(r, g, b);
  }



回答6:


HSL Color allows you to do this easily.



来源:https://stackoverflow.com/questions/5513690/map-rainbow-colors-to-rgb

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