correct way to render the spectrum color?

Started by
2 comments, last by Ohforf sake 12 years, 10 months ago
I want to use the spectrum color to render something, to describe the idea about height.(that is, more red means higher in some position)


I think I need to build a function F that maps a float to a RGB color. And F have to be increasive.(that is, if i < j then F( i ) < F( j ), F( j ) will be closer to the red than F( i ))

How can I achieve that?



I do know I can download an image of the spectrum and build the function using the width of the image. But I think it is not correct way to do that.
Advertisement
Looking up into an image is entirely sensible way to do it. Quite apart from anything, it means it's very easy to swap in another gradient later...
If you don't like the idea of indexing into a 1D texture that sweeps over the spectrum (why not?) then you can first map your float value into the HSV colour space, with a saturation and value of 1, and hue of 60..360 (you'll want to ignore the first 60 degrees otherwise you'll end up with red at both the low and high end of the scale). Then you simply convert HSV to RGB. There are plenty of resources on this so I won't go into details.

There's really nothing wrong with the texture lookup approach - it will be much simpler in a shader (only severaly lines of your chosen shader language), though you might find the HSV->RGB approach better suited if you're doing this on the CPU.
This is what I like to use (outside of shaders obviously). Just swap the vector class to whatever you use:


inline Vector3f ColorRamp(float f) {
Vector3f color;
if (f < 0.0) {
color[0] = 0;
color[1] = 0;
color[2] = 1.0;
return color;
}
if (f < 0.25) {
color[0] = 0;
color[1] = f / 0.25;
color[2] = 1.0;
return color;
}
if (f < 0.5) {
color[0] = 0;
color[1] = 1.0;
color[2] = (0.75-f) / 0.25;
return color;
}
if (f < 0.75) {
color[0] = (f-0.5) / 0.25;
color[1] = 1.0;
color[2] = 0;
return color;
}
if (f < 1.0) {
color[0] = 1.0;
color[1] = (1.0-f) / 0.25;
color[2] = 0;
return color;
}
color[0] = 1.0;
color[1] = 0;
color[2] = 0;

return color;
}


It is somewhat based on http://paulbourke.ne...our/colourramp/

This topic is closed to new replies.

Advertisement