Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

c# - Algorithm: How do I fade from Red to Green via Yellow using RGB values?

I want to display a color based on a value from 0 to 100. At one end (100), it's pure Red, the other end (0), pure Green. In the middle (50), I want it to be yellow.

And I want the colors to fade gradually from one to another, such that at 75, the color is half red and half yellow, etc.

How do I program the RGB values to reflect this fading? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had the same need and I just resolved with this:

myColor = new Color(2.0f * x, 2.0f * (1 - x), 0);

Explanation: Instead of the [0-255] range, let's focus on the [0.0-1.0] range for color components:

  • Green = 0.0, 1.0, 0.0
  • Yellow = 1.0, 1.0, 0.0
  • Red= 1.0, 0.0, 0.0

If you just scale the green component from 0.0 (on one end) to 1.0 (on the other end) and do the same thing with the red component (but going backwards), you'll get ugly and non-uniform color distribution.

To make it look nice, we could write a lot of code, or we could be more clever.

If you look carefully at the single components, you can see that we can split the range in two equal parts: in the first one we increase the red component from 0.0 to 1.0, leaving the green at 1.0 and the blue at 0.0; in the second we decrease the green component, leaving the other 2 as they are. We can take advantage of the fact that any value above 1.0 will be read as 1.0, by maxing out our values to simplify the code. Assuming your x value goes from 0.00 (0%) to 1.00 (100%), you can multiply it by 2 to let it go over the 1.0 limit for color components. Now you have your components going from 0.0 to 2.0 (the red one) and from 2.0 to 0.0 (the green one). Let them be clipped to [0.0-1.0] ranges and there you go.

If your x moves in another range (like [0-100]) you need to choose an appropriate factor instead of 2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...