I am trying to paint a WPF control's background based on a palette where each color has been assigned with values (e.g. Red = 0, DarkGreen = 10, Green = 20,LightGreen =30) and a user-selected value (e.g. 25) that would give the resulting color. I would like the resulting color to be an interpolation between the 2 nearest color values (e.g. for a value of 25 it should give a color between Green and LightGreen)
For that I'm thinking of using the existing LinearGradientBrush in WPF; set the GradientStops, offsets and get the color at a specified value . Is there a way to do this or should I implement my own color interpolation function?
Thanks.
I'm not sure if this was the case back then but in .NET 4.0 getting a color from a LinearGradientBrush can be done.
This would work with a brush configured as follows (for example):
Source: http://dotupdate.wordpress.com/2008/01/28/find-the-color-of-a-point-in-a-lineargradientbrush/
Using the LinearGradientBrush sounds like it would have a bit of an overhead. No knowledge though. A color interpolation function isn't that hard to write though.
I'm assuming your palettes have values that are divisible by 10 for simplicity.
If the defined colors are not divisible by 10 the logic to find the start and end colors will be a bit more complex.
Thanks for all the replies guys. It seems there is no way to get the "value" of a GradientBrush at a specified point. I hope this is corrected at some later version of the framework. So I guess the only option for now is to implement an interpolation algorithm as Mikko suggested.
I think you'll be better of using a value converter, just take one of the interpolation functions suggested in the other answers and put in in a value converter, use this converter to bind the background property to the value and you're done.
Where did you come up with the Values 10/20/30 for your DarkGreen/Green/Lightgreen colors.
You'll need some sort of correlation table between your assigned palette values & the real numeric representations of the colors... e.g.
From that correlation table, you could take any user "palette code", find the closed matching pair of palette codes from the table above and do a best-match range find on it. e.g. if some entered
25
(let's use HSL for convenience) then the formula would be...25 is halfway between both codes so
If they had selected
6
, you'd need to find .6 of the range of colors between each value.