简体   繁体   中英

Generating Color Gradient

I want to display to my user how many (percent wise) of their forms are compliant with the new standard. The way I want to let them know visually is the percent amount will be colored. It will be 0xFF0000 (pure red) for 0% and 0x00FF00 (pure green) at 100%. What is the best way to calculate the color for each step along the way?

Colour space conversion (as suggested by Tony ) will give you the best results. If however this is beyond the scope of what you are looking for, I suggest a simple algorithm that gets you yellow (0xFFFF00) for 50 %:

For values up to 50 % Start with 0xFF0000.
Add 0xFF * Percentage / 50 to the green component.

For values above 50 % Start with 0xFFFF00.
Subtract 0xFF * Percentage / 50 from the red component.

The results look good enough for my customers ;-)

You don't need to calculate it yourself - try using a LinearGradient brush. ( msdn )

LinearGradientBrush linGrBrush = new LinearGradientBrush(
   new Point(0, 10),
   new Point(200, 10),
   Color.FromArgb(255, 255, 0, 0),   // Opaque red
   Color.FromArgb(255, 0, 0, 255));  // Opaque blue

Pen pen = new Pen(linGrBrush);

e.Graphics.DrawLine(pen, 0, 10, 200, 10);
e.Graphics.FillEllipse(linGrBrush, 0, 30, 200, 100);
e.Graphics.FillRectangle(linGrBrush, 0, 155, 500, 30);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM