using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Media; using System.Diagnostics; namespace Microsoft.Research.DynamicDataDisplay.Common.Palettes { /// /// Represents a color step with its offset in limits [0..1]. /// [DebuggerDisplay("Color={Color}, Offset={Offset}")] public class LinearPaletteColorStep { /// /// Initializes a new instance of the class. /// public LinearPaletteColorStep() { } /// /// Initializes a new instance of the class. /// /// The color. /// The offset. public LinearPaletteColorStep(Color color, double offset) { this.Color = color; this.Offset = offset; } /// /// Gets or sets the color. /// /// The color. public Color Color { get; set; } /// /// Gets or sets the offset. /// /// The offset. public double Offset { get; set; } } /// /// Represents a palette with start and stop colors and intermediate colors with their custom offsets. /// public class LinearPalette : IPalette { /// /// Initializes a new instance of the class. /// /// The start color. /// The end color. /// The steps. public LinearPalette(Color startColor, Color endColor, params LinearPaletteColorStep[] steps) { this.steps.Add(new LinearPaletteColorStep(startColor, 0)); if (steps != null) this.steps.AddMany(steps); this.steps.Add(new LinearPaletteColorStep(endColor, 1)); } private readonly List steps = new List(); #region IPalette Members /// /// Gets the color by interpolation coefficient. /// /// Interpolation coefficient, should belong to [0..1]. /// Color. public Color GetColor(double t) { if (t < 0) return steps[0].Color; if (t > 1) return steps[steps.Count - 1].Color; int i = 0; double x = 0; while (x <= t) { x = steps[i + 1].Offset; i++; } Color c0 = steps[i - 1].Color; Color c1 = steps[i].Color; double ratio = (t - steps[i - 1].Offset) / (steps[i].Offset - steps[i - 1].Offset); Color result = Color.FromRgb( (byte)((1 - ratio) * c0.R + ratio * c1.R), (byte)((1 - ratio) * c0.G + ratio * c1.G), (byte)((1 - ratio) * c0.B + ratio * c1.B)); return result; } public event EventHandler Changed; #endregion } }